简体   繁体   English

如何使用jQuery获取列表中的特定项目?

[英]How to get specific item in list with jQuery?

I have the following generic list.我有以下通用列表。 How do I pull a single, specific item from this list?如何从此列表中提取单个特定项目?

<ul>
  <li id="t1">topic 1</li>
  <li id="t2">topic 2</li>
</ul>

jQuery: jQuery:

$li = $( "li" ).get(1);
console.log (($li).value());

Example: http://jsfiddle.net/5p86Lbpz/1/示例: http : //jsfiddle.net/5p86Lbpz/1/

Error:错误:

0 is not a function 0 不是函数

I'm following the pattern from here: https://api.jquery.com/get/ .我正在遵循这里的模式: https : //api.jquery.com/get/

  1. When you do get() , a native javascript DOM element is returned当您执行get() ,将返回本机 javascript DOM 元素
  2. When value is applicable, it is a property , not a functionvalue适用时,它是一个属性,而不是一个函数
  3. For li elements, there is no value property, rather textContent对于li元素,没有value属性,而是textContent

 $li = $("li").get(1); console.log($li.textContent);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li id="t1">topic 1</li> <li id="t2">topic 2</li> </ul>

您也可以使用eq() ,在我看来它比get()更好,因为它将元素作为 jQuery 对象返回,因此您可以在它上面使用 jQuery 函数,例如text()

$("li").eq(1).text();

尝试:

jQuery("li:first").html(); //This will return "topic 1"

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

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