简体   繁体   English

使用jQuery更改第一个跨度的文本

[英]change the text of the first span with jQuery

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: 我的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. .prev()方法在DOM树中搜索每个这些元素的前身,并从匹配的元素构造一个新的jQuery对象。

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 摘自JQuery prev文档

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 参见http://jsbin.com/leyasiwexu/edit?html,js,输出

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 . 我没有检查, HTML规格 ,但我不认为它适合筑巢一个divli I know you can work your way around presentation irregularities with css, but this might not be permissible with jQuery. 我知道您可以使用CSS解决呈现不规则的问题,但是jQuery可能不允许这样做。 Just as I said, I haven't verified. 就像我说的,我还没有验证。 If you have to nest items inside li , use inline elements. 如果必须在li 嵌套项目,请使用内联元素。 div is block div

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM