I've tried a number of things but I cannot get my code to work. I want to change the text of the span containing a number in this code:
<li class="top">
<div class="sec">
<span>123</span>
<span class="inner">Lorem</span>
</div>
</li>
My JavaScript/JQuery:
(function($) {
$(document).ready(function() {
$('li.top .sec').find('span').eq(0).text('cccc');
});
})(jQuery);
I've been able to write code that changes both spans, but not the one.
(function($) { $(document).ready(function() { $('li.top .sec').find('.inner').prev().text('cccc'); }); })(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li class="top"> <div class="sec"> <span>123</span> <span class="inner">Lorem</span> </div> </li>
the
.prev()
method searches for the predecessor of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements.The method optionally accepts a selector expression of the same type that can be passed to the $() function. If the selector is supplied, the preceding element will be filtered by testing whether it match the selector.
Excerpt taken from the JQuery prev
documentation
Your code body appears to work to largely work.
I just tried inserting this line into the doc as follows:
$('li.top .sec').find('span').eq(0).text('cccc');
See http://jsbin.com/leyasiwexu/edit?html,js,output
So, perhaps there is something else that is causing the issue?
console.log($('li.top .sec').find('span').eq(0).text()); $('li.top .sec').find('span').eq(0).text('cccc') console.log('changed to: ' + $('li.top .sec').find('span').eq(0).text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li class="top"> <div class="sec"> <span>123</span> <span class="inner">Lorem</span> </div> </li>
您可以尝试以下方法:
$('li.top .sec').find('.inner').prev().text('cccc');
I haven't checked, HTML Specifications , but I don't think its appropriate to nest a div
inside li
. I know you can work your way around presentation irregularities with css, but this might not be permissible with jQuery. Just as I said, I haven't verified. If you have to nest items inside li
, use inline elements. div
is block
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.