所以,我有一个网站,并且只有一些类可以用来隔离我想要编辑的元素。我需要在 html 中找到一个包含特定字符串的元素,并替换它的同级 html 之一。无论如何,这是我得到的代码:
if((".user.info").html().indexOf(vaUID[index]) >= 0) {
$("a.user.info").each(function (index2, obj) {
if($(this).html().indexOf(vaUID[index]) >= 0) {
$(this).siblings('.registered').html('<div class="registered"><a href=http://www.twitch.tv/'+users[index]+ '>currently streaming' + data.stream.game + '</a></div>');
}
});
}
这是起始 html:
<div class="user first">
<div class="element_avatar simple small "><a href="http://www.cnr-clan.com/profile/xxxxxx" data-minitooltip="username"><img src="http://assets-cloud.enjin.com/users/xxxxxx/avatar/small.xxxxxx.png"></a></div>
<div class="info">
<a href="http://www.cnr-clan.com/profile/xxxxxx" class="element_username tag-xxxxxx">username</a>
<span class="nameicons">
<!--Irrelevant Excess Code-->
</span>
<div class="registered">currently browsing</div>
</div>
<div class="clearing"><!-- --></div>
</div>
我想要的结果是:
<div class="user first">
<div class="element_avatar simple small "><a href="http://www.cnr-clan.com/profile/xxxxxx" data-minitooltip="username"><img src="http://assets-cloud.enjin.com/users/2219573/avatar/small.xxxxxx.png"></a></div>
<div class="info">
<a href="http://www.cnr-clan.com/profile/xxxxxx" class="element_username tag-xxxxxx">username</a>
<span class="nameicons">
<!--Irrelevant Excess Code-->
</span>
<div class="registered"><a href='http://www.twitch.tv/username'>currently streaming gamename</a></div>
</div>
<div class="clearing"><!-- --></div>
</div>
请记住,我在同一个类中有几个这样的代码块。 vaUID[index] 的示例值为 xxxxxx。
最佳答案
我建议,基于该 HTML:
// selects the appropriate elements:
$('.user .info a.element_username')
// filters that collection:
.filter(function(){
// retains only those in which this assessment results as true/truthy
return $.trim($(this).text()) === 'username';
})
// searches amongst those retained-elements' sibling for those that match
// the passed-selector:
.siblings('div.registered')
// wraps the contents of those elements with the supplied HTML:
.wrapInner('<a href="http://www.twitch.tv/username"></a>');
上述 filter()
条件将仅保留那些文本内容与 'username'
字符串精确匹配的元素 (demo to highlight that problem );要保留那些仅包含该字符串的内容,您可以将 filter()
修改为:
return $(this).text().indexOf('username') > -1; // this is case-sensitive
或者:
return $(this).text().toLowerCase().indexOf('username') > -1; // this is case-insensitive
引用文献:
-
filter()
. -
jQuery.trim()
. -
siblings()
. -
text()
. -
wrapInner()
.
关于javascript - 查找包含字符串的元素并替换同级元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22243734/