[英]Jquery / Javascript find closest span with custom attribute and change inner html
使用JQuery和/或Javascript,我该怎么做-
我需要找到具有等于某个值的自定义属性的<span>
。 然后,我需要将内部<span>
设置为等于某些文本。
示例:在下面的html中,我需要使用属性data-my-custom-attribute == Value1查找跨度,并在内部跨度中填充一些文本。
<span data-my-custom-attribute="Value1" >
<span> /**put text here***/ </span>
</span>
<span data-my-custom-attribute="Value2" >
<span> /**leave empty***/ </span>
</span>
如果div
始终是该属性的span
的同级兄弟,则可以使用此属性。
$('#MyDiv').nextAll('[data-my-custom-attribute="ValueX"]:first').find('span').text('something');
我想您只需要:
$('[data-my-custom-attribute="Value1"] span').text('something');
使用CSS兄弟姐妹选择器~
$('#MyDiv ~ [data-my-custom-attribute="Value1"] > span').text('BOOH!')
编辑用于选择内部跨度
$('#MyDiv').siblings('span[data-my-custom-attribute]:first > span').text("text goes here");
根据您原来的问题(和更新的问题),以下两种方法都可以找到span
:
// works because your custom attribute is a data attribute
$('span').filter(function (i) {
return $(this).data('my-custom-attribute') === 'Value1';
}).children('span').text('yay! new text');
// works regardless of what the custom attribute is
$('span[data-my-custom-attribute="Value1"]').children('span').text('yay! new text');
// or
$('span[my-custom-non-standardized-html-attribute="Value1"]').children('span').text('yay! new text');
这是一个小提琴演示: http : //jsfiddle.net/ucq94/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.