javascript - 如何选择这种格式的动态 ID?

标签 javascript jquery

当用户在输入字段中输入内容时,我正在尝试选择动态 ID。我的应用程序输出以下格式的输入字段:

<input id="student_1_first_name" />
<input id="student_1_last_name" />

<input id="student_2_first_name" />
<input id="student_2_last_name" />

<input id="student_3_first_name" />
<input id="student_3_last_name" />

etc.

例如,我尝试这样做来选择 id 字符串的结尾:

<script type="text/javascript">
  $(document).ready(
  function (){
    $("input[id$=_first_name]").bind("keyup", run_some_function_here);
    run_some_function_here();
    $("input[id$=_last_name]").bind("keyup", run_some_function_here);
    run_some_function_here();
  }
);
</script>

当我这样做时,Jquery 似乎无法选择输入 ID,因此函数不会运行。您对我如何正确选择 ID 有什么想法吗?

最佳答案

为每个输入分配类别,例如 <input id="student_1_first_name" class="input-class" />

然后试试这个

$(function() {
   $('input.input-class').each(function() {
       var id = $(this).attr('id');
   });
});

关于javascript - 如何选择这种格式的动态 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2671996/

相关文章:

javascript - Rails Controller 操作可以同时处理 html 和 javascript 请求吗?

javascript - 突出显示 Li 中 , 之后的搜索文本

javascript - 忽略php中的javascript错误

jquery - 从 CSS 类中选择属性

javascript - CSS - 表格数据不在固定表格标题下

javascript - 如何向我的网站添加 HTML 代码,以便当人们单击它时,它会打开与我的 WhatsApp 对话?

javascript - 找不到模块无法解析

jquery - 通过 JQuery 重用相同的 html/css 代码

javascript - 当我使用 jQuery 将事件处理程序添加到 html 中的对象时,是否必须调用 $.ready(function(){ ... })?

javascript - jQuery 克隆问题