【发布时间】:2014-05-24 04:16:18
【问题描述】:
首先大家好,对不起我的英语。
我仍然会利用这个社区的专业知识和可用性。
昨天我看到一个关于字符串组织的帖子(this)。
为简单起见,我们删除表格并尝试查看以下代码
<div id="find">
<div>(this match)</div>
<div>(this match)</div>
<div>some text1
<div></div>
<div>(this match)</div>
<div>some text2</div>
<div>some text3</div>
</div>
</div>
在这种情况下,如果我们想查找包含单词“match”的项目并将该单词替换为“some other text”字符串,我们可以使用通过阅读有关该主题的其他帖子找到的这些代码之一
$(document).ready(function(){
var elements = $('div');
for(var i = 0; i < elements.length; i++) {
var current = elements[i];
if(current.children.length === 0) {
var x=current.textContent
if (x.indexOf('match') > 0) {current.textContent='some other text'}
}
}
})
$(document).ready(function(){
$("#find div:contains('match'):not(:has(*))").each(function () {
var str=$(this).text('some other text')
})
})
$(document).ready(function(){
$("div").each(function(){
var str=''
var div = $(this).clone();
div.find("*").remove();
str=div.text();
if (str.indexOf('match') > 0) {
$(this).text('some other text')
}
})
})
但是,如果您以这种方式编辑 html,所有 sn-ps 都是错误的
<div id="find">(this match)
<div>(this match)
<div>(this match)</div>
</div>
<div>(this match)<div>aaaa</div></div>
<div>some text1
<div></div>
<div>(this match)</div>
<div>some text2</div>
<div>some text3</div>
</div>
</div>
我已找到解决此问题的方法,但我认为它不优雅且过于冗长
$(document).ready(function(){
var len =$('#find div').length
for(i=1;i<len;i++){
$('div:eq('+i+')').contents().addClass('passed').filter(function () {
return $(this).text()==='(this match)' && $.trim(this.nodeValue).length
}).replaceWith('some other text');
}
for(i=0;i<len;i++){
var classx=$('div:eq('+i+')').attr('class')
if(classx===undefined){
var xx=$('div:eq('+i+')').contents()[0].nodeValue
if (xx.indexOf('match') > 0) {
$('div:eq('+i+')').contents()[0].nodeValue='some other text'
}
}
}
})
请有人指导我采用更有效和更优雅的方式来实现相同的结果吗?
与往常一样,提前谢谢大家,任何建议都将受到欢迎。
【问题讨论】:
-
'indexOf'的返回值是你的字符串的第一个字母的位置,当字符串没有找到时,返回的值是-1。检查你的代码;)
-
@queval_j:可能我没有理解你的评论,但如果我写 x.indexOf('match') > -1 那 sn-p 不适用于第二个 html sinppet。跨度>
-
不是解决方案,而是less中的问题。
标签: javascript jquery string replace