如何检查选择框是否被抓取并使用Jquery获取其ID



我正在尝试查看是否有任何selectbox被jquery抓取,然后从中获取它的id,我有多个名称相同但id不同的框,这些框是通过php派生的。例如number1,例如数字+整数。

我想检查/注册一个事件,在该事件中,单击任何选择框时,id都会被抓取并放入变量中,以便稍后操作。

有点像

if ($('select').clicked) {
var sID = $('select').getID();
// use id to see which selectbox has been clicked.
}

以上需要动态发生,例如,我们不知道选择框,所以我们需要一个事件来检查是否点击了任何选择,然后获取它的ID。

我有大约20个选择框,不想单独检查,因为这占用了太多空间,未来可能会有更多的选择框。

p.S.这可能吗?

使用jQuery实际上很容易。使用on((方法在每个选择上附加一个点击处理程序,并使用$(this)获取当前点击的内容。

$(document).ready(function(){
$('select').on('click',function(){
console.log($(this).attr('id'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="s1">
<option>1</option>
</select>
<select id="s2">
<option>1</option>
</select>
<select id="s3">
<option>1</option>
</select>

变量在每个"输入";事件,所以它基本上是用户最后使用的<select>的警报。它不会在刚点击时触发,用户必须选择一个值,如果选择了与以前相同的值,那么它也不会触发。

下面的示例中对详细信息进行了评论

// Utility function for demo
const log = data => console.log(JSON.stringify(data));
// Reference the form
const form = document.forms[0];
// Register input event to form
form.oninput = xIds;
/* 
If you just want the last select user has used just declare a variable
*/
let x;
// Event handler
function xIds(e) {
/*
The select user is picking a value from
*/
const active = e.target;
/*
If the select has the name 'x'...
...assign active id to variable x.
*/
if (active.name === 'x') {
x = active.id;
log(x);
}
}
.as-console-row::after {
width: 0;
font-size: 0;
}
.as-console-row-code {
width: 100%;
word-break: break-word;
}
.as-console-wrapper {
min-height: 100%;
max-width: 50%;
margin-left: 50%;
}
<form>
<select id='x1' name='x'>
<option selected disabled>Select an option</option>
<option>0</option>
<option>1</option>
</select><br>
<select id='x2' name='x'>
<option selected disabled>Select an option</option>
<option>0</option>
<option>1</option>
</select><br>
<select id='x3' name='x'>
<option selected disabled>Select an option</option>
<option>0</option>
<option>1</option>
</select><br>
<select id='x4' name='x'>
<option selected disabled>Select an option</option>
<option>0</option>
<option>1</option>
</select><br>
<select id='x5' name='x'>
<option selected disabled>Select an option</option>
<option>0</option>
<option>1</option>
</select>
</form>

您可以在jQuery中完成。首先,您需要为所有选择框添加一个更改事件侦听器

例如:

$('select').change(function(){
var sID = $(this).attr('id'); })
or you can also use 
$('select').on('click',function(){
var sID = $(this).attr('id'); })
})

最新更新