簡體   English   中英

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

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

我已經嘗試了很多方法,但是我無法使代碼正常工作。 我想更改此代碼中包含數字的跨度文本:

<li class="top">
  <div class="sec">
            <span>123</span>
            <span class="inner">Lorem</span>
    </div>
</li>

我的JavaScript / JQuery:

(function($) {
  $(document).ready(function() {
    $('li.top .sec').find('span').eq(0).text('cccc');
  });
})(jQuery);

我已經能夠編寫更改兩個跨度的代碼,但不能更改一個。

 (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> 

.prev()方法在DOM樹中搜索每個這些元素的前身,並從匹配的元素構造一個新的jQuery對象。

該方法可選地接受可以傳遞給$()函數的相同類型的選擇器表達式。 如果提供了選擇器,則將通過測試前一個元素是否與選擇器匹配來對其進行過濾。

摘自JQuery prev文檔

您的代碼主體似乎在很大程度上起作用。

我只是嘗試將此行插入到文檔中,如下所示:

 $('li.top .sec').find('span').eq(0).text('cccc');

參見http://jsbin.com/leyasiwexu/edit?html,js,輸出

因此,也許還有其他原因導致了此問題?

 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');

我沒有檢查, HTML規格 ,但我不認為它適合築巢一個divli 我知道您可以使用CSS解決呈現不規則的問題,但是jQuery可能不允許這樣做。 就像我說的,我還沒有驗證。 如果必須在li 嵌套項目,請使用內聯元素。 div

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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