[英]Jquery / Javascript find closest span with custom attribute and change inner html
Using JQuery and/or Javascript how would I do the following - 使用JQuery和/或Javascript,我该怎么做-
I need to find the <span>
which has a custom attribute equal to a certain value. 我需要找到具有等于某个值的自定义属性的<span>
。 I then need to set the inner <span>
equal to some text. 然后,我需要将内部<span>
设置为等于某些文本。
Example: In the html below, I need to find the span with attribute data-my-custom-attribute == Value1 and fill the inner span with some text. 示例:在下面的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>
You can use this if the div
will always be a sibling of the span
with the attribute. 如果div
始终是该属性的span
的同级兄弟,则可以使用此属性。
$('#MyDiv').nextAll('[data-my-custom-attribute="ValueX"]:first').find('span').text('something');
I guess you only need that : 我想您只需要:
$('[data-my-custom-attribute="Value1"] span').text('something');
Use the css siblings selector ~
使用CSS兄弟姐妹选择器~
$('#MyDiv ~ [data-my-custom-attribute="Value1"] > span').text('BOOH!')
edited for selecting the inner span 编辑用于选择内部跨度
$('#MyDiv').siblings('span[data-my-custom-attribute]:first > span').text("text goes here");
Based on your original (and updated) question, either of these methods should work to find the span
s: 根据您原来的问题(和更新的问题),以下两种方法都可以找到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');
Here's a fiddle demo: http://jsfiddle.net/ucq94/ 这是一个小提琴演示: http : //jsfiddle.net/ucq94/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.