【问题标题】:jquery - how to add an variable as an id in jquery command.? [duplicate]jquery - 如何在 jquery 命令中添加变量作为 id。? [复制]
【发布时间】:2013-06-07 10:06:49
【问题描述】:

这是一个简单的问题,无法从谷歌找到答案。

代码

$.click(function(){
var curID = $(this).parent()[0].id;
$("#"+curID input).attr("checked",true);
});

Onclick 函数给了我父 ID,现在,我想使用父 ID 查找输入元素并添加选中的属性。

我不确定dynamic ID 查询的语法。

我想知道如何通过动态变量查询。

提前致谢。

【问题讨论】:

  • 你能提供HTML吗?我很难理解您的要求..
  • $.click 会抛出错误,因为该函数不存在。您需要实际选择元素以将点击事件绑定到。

标签: javascript jquery


【解决方案1】:
$("#"+curID).find('input').attr("checked", true);

或者

$(this).parent().find('input').attr("checked", true);

或者

$('input', $(this).parent()).find('input').attr("checked", true); // using the scope argument

【讨论】:

    【解决方案2】:

    选择器是字符串......所以应该通过连接变量来作为字符串处理:和文本

    $.click(function(){
    var curID = $(this).parent()[0].id;
    $("#"+curID+" input").attr("checked",true);
    });
    

    【讨论】:

      【解决方案3】:

      您的搜索可能过于具体。将任务分解为其组成部分,而不是为一个非常具体的问题寻找完整的解决方案。您只是在这里处理基本的字符串连接。

      你想要:

      var selector = "#foo input";
      

      您的变量中有foo

      var selector = "#" + foo_variable + " input";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-18
        • 1970-01-01
        • 1970-01-01
        • 2017-04-09
        • 1970-01-01
        • 2014-05-30
        • 2020-03-19
        相关资源
        最近更新 更多