简体   繁体   English

如何获取下一个span元素的文本?

[英]How do I get the text of the next span element?

Below is my HTML. 以下是我的HTML。 I'm at the <select> element, how do I get the text from the next span element on the page? 我在<select>元素上,如何从页面上的下一个span元素获取文本? I've tried several things, including $( this ).nextAll( 'span:first' ).text(); 我已经尝试了几件事,包括$( this ).nextAll( 'span:first' ).text(); where $( this ) is my select element, but I'm not getting the desire result. $( this )是我的select元素,但是我没有得到期望的结果。

<ul id="questions">
   <div>What do you want information about?</div>
   <li>
      <p>
         <select><!-- This is where I'm at. -->
            <option>Click to select...</option>
            <option data-next_select_name="foos">
               a foo
            </option>
            <option data-next_select_name="bars">
               a bar
            </option>
         </select>
      </p>
      <div>
         <a>
            <span>a foo</span><!-- I want the text out of this span. -->
            <div><b></b></div>
         </a>
         <div>
            <div><input type="text" /></div>
            <ul>
               <li>Click to select...</li>
               <li>
                  a foo
               </li>
               <li>
                  a bar
               </li>
            </ul>
         </div>
      </div>
      <p></p>
   </li>
</ul>

nextAll选择元素的下一个同级,span元素不是nextAll元素的同级之一:

$(this).parent().next().find('span:first').text()

Just incase your html structure changes and .next() isn't an option, I always prefer to go up to the definitive parent (in this case the list-item) 万一您的html结构发生变化并且.next()不是一个选择,我总是更喜欢使用确定的父级(在这种情况下为list-item)

$(this).closest('li')
       .find('span').first().text();

Random side note: .first() is faster than :first 随机注释: .first():first

$( this ).parent().next().find('span:first').text()

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

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