使用jquery在属性中搜索字符串

时间:2014-12-11 19:34:58

标签: javascript jquery

我有不同的属性,包含相同的文本字符串。像:

<div id="outer">
<div id="carousel-example-generic"></div>
<div data-target="#carousel-example-generic"></div>
<a href="#carousel-example-generic" ></a>
</div>

如何找到并重命名&#34; carousel-example-generic&#34;使用jquery在那些元素上?

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

$(document.documentElement).html(function(i,val){
    return val.replace(/carousel-example-generic/g,'my-new-string');
});

...但要小心,这将替换文档中的字符串无处不在:标签,文本,值,无处不在。此外,正如下面Salman所说,事件处理程序也会被破坏,包括父元素。

鉴于上面的示例,此处显示的代码产生以下html:

<div id="outer">
<div id="my-new-string">asdfasdf</div>
<div data-target="#my-new-string">asdfadsfad</div>
<a href="#my-new-string">asdfasdfa</a>
</div>

这里是fiddle。检查元素以查看更改。

答案 1 :(得分:0)

以下是一种方法:

// iterates over each of the descendant elements of '#outer':
$('#outer *').each(function() {
  // iterates over the array-like 'this.attributes' (list of the element's attributes)
  // property, using Array.prototype.forEach, 'a' is the array-element itself:
  Array.prototype.forEach.call(this.attributes, function(a) {
    // setting the value of the attribute:
        // if the string 'carousel-example-generic' is found within the attribute-value,
        // we replace that string with 'new-string', otherwise
        // return the current attribute-value:
    a.value = a.value.indexOf('carousel-example-generic') > -1 ? a.value.replace('carousel-example-generic', 'new-string') : a.value;
  });
});

&#13;
&#13;
$('#outer *').each(function() {
  Array.prototype.forEach.call(this.attributes, function(a) {
    a.value = a.value.indexOf('carousel-example-generic') > -1 ? a.value.replace('carousel-example-generic', 'new-string') : a.value;
  });
});

$('#result').text($('#outer').html());
&#13;
#result {
  white-space: pre-wrap;
  font-family: monospace;
  border: 1px solid #f90;
  margin-top: 1em;
  position: relative;
  padding: 0.5em;
}
#result::before {
  content: 'HTML converted to:';
  border: 1px solid #f90;
  background-color: #fff;
  position: absolute;
  top: -1em;
  left: 0.5em;
  height: 2em;
  line-height: 2em;
  padding: 0 0.2em;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer">
  <div id="carousel-example-generic"></div>
  <div data-target="#carousel-example-generic"></div>
  <a href="#carousel-example-generic"></a>

</div>
<div id="result"></div>
&#13;
&#13;
&#13;

参考文献: