在字符串上处理 jQuery/Sizzle 查询

Process jQuery/Sizzle queries on string?

本文关键字:Sizzle 查询 jQuery 处理 字符串      更新时间:2023-09-26

我有一个来自服务器的字符串,我需要在将其添加到DOM之前对其进行修改。我想替换<div data-role="placeholder" />有很多格式(换行符等)和额外属性。

这是我的字符串示例:

 <span title="15 gold badges"><div data-role="placeholder" /></span>
 <span title="25 starts"><div data-role="placeholder" id="test"></div></span>

如何查询占位符并将其替换为另一个 HTML 字符串,例如 <div data-role="calendar" />

我可以看到两种方法。你要么使用旧的.replace(),要么把它包装在一个jQuery对象中,然后使用DOM操作方法。

使用字符串替换

var html = '<span title="15 gold badges">' +
  '<div data-role="placeholder" />' +
  '</span><span title="25 starts">' +
  '<div data-role="placeholder" id="test">' +
  '</div></span>';
$('body').append(html.replace(/data-role="placeholder"/g, 'data-role="calendar"'));
$('div[data-role=calendar]').text('yay!');
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

使用 jQuery 方法

var html = '<span title="15 gold badges">' +
  '<div data-role="placeholder" />' +
  '</span><span title="25 starts">' +
  '<div data-role="placeholder" id="test">' +
  '</div></span>';
$(html).find('[data-role]').attr('data-role', 'calendar').end().appendTo('body');
$('div[data-role=calendar]').text('yay!');
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>