jQuery 如何使用jquery获取两个div的li值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7696045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:10:44  来源:igfitidea点击:

How to get value of li value of two div's using jquery

jquery

提问by Fero

Please find the below structure.

请找到以下结构。

When i click a button i need to get the li value of two div.

当我单击一个按钮时,我需要获取两个 div 的 li 值。

For example, Let us consider in first div i have selected test2and in second div i have selected test 8and when i click the button i need to get the value as 558 and 561

例如,让我们考虑在第一个 div 中我选择了 test2在第二个 div 中我选择了 test 8当我单击按钮时,我需要获得 558 和 561 的值

How can i do this using jquery.

我如何使用 jquery 做到这一点。

<div class='parent'>test 1</div>
<div class="list">
    <ul>
    <li value="0">All</li>
    <li value="556">test 1</li>
    <li value="558">test 2</li>
    <li value="560">test 3</li>
    <li value="561">test 4</li>
    </ul>  
</div>

<div class='parent2'>test 6</div>
<div class="list2">
<ul>
<li value="0">All</li>
<li value="556">test 5</li>
<li value="558">test 6</li>
<li value="560">test 7</li>
<li value="561">test 8</li>
</ul>  
</div>

Thanks in advance...

提前致谢...

回答by Darin Dimitrov

litags cannot be selected and do not have a valueattribute defined. It would be more correct to use radio buttons or a dropdown to select a value. If you want to use li you could keep 2 global variables with the corresponding selected values which will be updated everytime some li is clicked:

li无法选择标签且未value定义属性。使用单选按钮或下拉列表来选择一个值会更正确。如果你想使用 li,你可以保留 2 个全局变量和相应的选定值,每次单击某些 li 时都会更新:

var value1 = '0',
    value2 = '0';

$('.list li').click(function() {
    value1 = $(this).attr('value');
});

$('.list2 li').click(function() {
    value2 = $(this).attr('value');
});

$('#someButton').click(function() {
    alert('value1 = ' + value1 + ' | value2 = ' + value2);    
});

回答by Sheitan

If you are asking about "select" box instead of "li" tag, you can easily grab the select variable with jQuery using .val()

如果您问的是“选择”框而不是“li”标签,您可以使用 .val() 使用 jQuery 轻松获取选择变量