Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - 从li元素获取值属性(Get value attribute from an li element)

I have an unordered list with li elements in it.

(我有一个带li元素的无序列表。)

When I click on that particular item in the list, I want to extract the value of that li item and use it.

(当我单击列表中的特定项目时,我想提取该li项目的值并使用它。)

In the example below I would want to extract the value "9".

(在下面的示例中,我想提取值“ 9”。)

How can I do this in jQuery?

(如何在jQuery中做到这一点?)

<li sequence="1" title="Category 1" class="liEllipsis selSubCategories" value="9">
    <a href="#">
        <span class="viewIcons delFaceName _delete fl"></span>
        Category 1
    </a>
</li>
  ask by Gaurav Sachdeva translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Firstly, there is no value attribute available on an li element, and adding non-standard attributes will mean that your page is invalid.

(首先, li元素上没有可用的value属性,添加非标准属性将意味着您的页面无效。)

Instead, use data-* attributes.

(而是使用data-*属性。)

You can then hook to the click event of the a element and get that data attribute from its parent li , like this:

(然后,您可以挂钩到a元素的click事件,并从其父li获取该data属性,如下所示:)

 $('li a').click(function(e) { e.preventDefault(); var value = $(this).closest('li').data('value'); // = 9 console.log(value); // do something with the value here... }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li data-sequence="1" title="Category 1" class="liEllipsis selSubCategories" data-value="9"> <a href="#"> <span class="viewIcons delFaceName _delete fl"></span> Category 1 </a> </li> <li data-sequence="1" title="Category 2" class="liEllipsis selSubCategories" data-value="10"> <a href="#"> <span class="viewIcons delFaceName _delete fl"></span> Category 2 </a> </li> </ul> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...