在 select2 中,为什么我必须输入 $('select').val();到 click() 函数

In select2,why should I have to put the $('select').val(); to the click() function

本文关键字:select val 函数 click select2 为什么 输入      更新时间:2023-09-26

你知道,我只是学习select2。我需要获取所选选项的值,我知道我应该这样做:

$('select').val();

所以我只写一个简单的问题,这样:

.HTML:

<button id="clickIt">click</button>
<p>SELECT NUMBER</p>
<select id='first'>
<option value='1'>First</option>
<option value='2'>Second</option>
<option value='3'>three</option>
</select>
<p id="set1"></p>

我还添加了Jquery和select2库。

当我写JS时,我发现这个:

$(document).ready(function(){
$("#first").select2();
//var a=$("#first").val(); // it always alert 1,so a always equals 1.
$('#clickIt').on("click",function(){
var a=$('#first').val(); // that is the resule what I want .
alert(a);
})
})

我想知道为什么var a=$('#first').val(); 放另一个位置会产生另一个效果吗?

因为$("#first").val();返回当前选定的值而不是将来的值。因此,当您调用$("#first").select2();并尝试检索该值时,您将获得当前选定的值。

但是,当您在单击事件中调用$("#first").val();时,每次单击#clickIt时,都会调用$("#first").val();并返回新选择的值。

我希望这对你有意义。