javascript - jQuery 输入的动态名称

标签 javascript jquery

我对输入的自动名称有疑问,我会尝试解释我需要做什么。我有一个 id,我从外部函数得到它。我需要使用这个数字 ID 来创建另一个类似的函数。

var id = 10;  // this is the id (from external function)
var value = "n"+bar.toString(); // (I try to cast the id as string) 
$("input[name="+value+"]").on('change', function() { // use the cast value to name my input.
  alert($("input[name="+value+"]:checked", "#myForm").val()); 
});

当我尝试这样做时,我得到了 undefined,但是当我像那样更改 id 时 var id ="10" 我得到了正确的答案,但是我有一个数字输入。请帮我弄清楚如何解决这个问题。

最佳答案

你想要这样的东西吗?这是基于您在表单中有复选框的假设!

var ids = [10, 20, 30, 11, 12];
$.each(ids, function(index, val) {
    var id = val;
    var value = "n" + id; // `.toString` is not required!
    $("#myForm").find("input[name='"+value+"']").on('change', function() {
        if ($(this).is(":checked")) {
            alert( $(this).val() );
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
    <input type="checkbox" name="n10" value="10" />
    <input type="checkbox" name="n11" value="11" />
    <input type="checkbox" name="n12" value="12" />
</form>

关于javascript - jQuery 输入的动态名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29230917/

相关文章:

javascript - 首先显示选择最多的项目

javascript - 更改选择列表的选定值

javascript - 奇怪的 jQuery 错误 .children(...).attr(...).change 不是一个函数?

javascript - 如何在 Gatsby React 页面中使用 &lt;script&gt;

javascript - Document.body 不存在。 Modernizr 连字符测试需要它

javascript - 仅在没有其他监听器存在时才添加 Javascript EventListener?

jquery - 如何在 jQuery 对话框中使用 ui-state-error

javascript - 使用JQuery和PHP可以在浏览器上显示文本和图像吗?

javascript - getElementsByClassName Iexplorer 兼容性

javascript - 对于调用另一个异步函数的异步函数, Jest 测试失败