簡體   English   中英

jQuery / Javascript查找具有自定義屬性的最接近范圍並更改內部html

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM