Mic*_*ips 5 javascript c# jquery
如何从@for循环中检索值到jquery ..循环中的每个值都应该有不同的id,而jquery应该得到每个单独的id ....我的for循环,
@for (int i = 0; i < searchList.Count;i++ )
{
<label for="input@i"><input type="checkbox" id="input@i"/>@searchList[i] </label>
}
Run Code Online (Sandbox Code Playgroud)
我的jquery没有帮助,
$("#input@i").on("click", function () {
var currentChk = $(this);
var propCheck = currentChk.prop("checked");
if (propCheck) {
debugger;
var valChk = $("#input@i").val();
alert(valChk);
}
});
Run Code Online (Sandbox Code Playgroud)
提前致谢...
您可以使用Attribute Starts With Selector来绑定事件。
$("[id^=input]").on("click", function () {
var currentChk = $(this);
var propCheck = currentChk.prop("checked");
if (propCheck) {
debugger;
var valChk = $("#input@i").val();
alert(valChk);
}
});
Run Code Online (Sandbox Code Playgroud)
由于标签和输入复选框的 id 均以“input”开头,因此单击事件将绑定到它们。如果您想限制,可以向选择器添加类型,例如您只想在复选框上更改选择器,如下所示。
$("input[id^=input]").on("click", function () {...
Run Code Online (Sandbox Code Playgroud)
或者
$(":checkbox[id^=input]").on("click", function () {...
Run Code Online (Sandbox Code Playgroud)
如果将类分配给要附加事件的控件,则可以使用类选择器来绑定事件。
@for (int i = 0; i < searchList.Count;i++ )
{
<label for="input@i"><input type="checkbox" class="chk-class" id="input@i"/>@searchList[i] </label>
}
$(".chk-class").on("click", function () {...
Run Code Online (Sandbox Code Playgroud)
编辑正如 Mohamed-Yousef 指出的那样,您应该currentChk最好使用 or$(this)而不是$("#input@i")in 语句$("#input@i").val();,因为 @i 不会是 C# 循环的替换值,但它将作为字符串文字添加。
作为补充说明,您可以在可能且合适的情况下使用本机 javascript,例如我会使用 this.checked 而不是 currentChk.prop("checked") 以获得更好的性能、可读性和简单性。
$("[id^=input]").on("click", function () {
if (this.checked)
{
//your code
}
else
{
//your code
}
});
Run Code Online (Sandbox Code Playgroud)