EDIT: IT WAS A TYPO, I'VE OVERSEEN. Please ignore this question I want to select the data-key attribute from the span inside a li-element, when the checkbox is checked.
<li class="result-set-list-item">
<input class="result-select-checkbox" type="checkbox"></input>
<span class="list-item-content" data-key="foobar">Das Foobar</span>
</li>
Javascript:
$('#result-list-ul li').each(function () {
if ($(this).find('.result-select-checkbox').attr('checked') == 'checked') {
console.log($(this).children("span").first().data['key']); }
...
Even when $(this).children("span")
returns an valid array including the span, I cannot access the data-attribute using (this).children("span").first().data['key']
How should I access the span in this case? I got lots of elements and I don't want to implement an id for each span.
像函数一样调用
$(this).children("span").first().data('key');
So
$('#result-list-ul li').each(function () {
if ($(this).find('.result-select-checkbox').is(':checked')) {//use :checked to see if checked
console.log($(this).children("span").first().data('key'));//use () to call the data function
}
A shortened version is
$('#result-list-ul li:has(.result-select-checkbox:checked)').each(function () {
//will execute only for li's with checked items
console.log($(this).children("span").first().data('key')); //use () to call the data function
})
data is a method in jQuery and not an object/array
. Use it by passing the key in like
console.log($(this).children("span").first().data('key'));
$('li').each(function() { console.log($(this).children("span").first().data('key')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <li class="result-set-list-item"> <input class="result-select-checkbox" type="checkbox"></input> <span class="list-item-content" data-key="foobar">Das Foobar</span> </li>
To select the checked boxes
var cb = $('.result-select-checkbox:checked', this)
To get the value of the data attribute
$(cb).data('key')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.