【问题标题】:how to assign variable as div name in jquery如何在jquery中将变量分配为div名称
【发布时间】:2014-08-04 07:32:57
【问题描述】:

当单击链接时,我调用ajax 方法,该方法将返回数据为object。在将有我的组名的数据中。我正在尝试empty the group and create a new div,但我收到错误请让我知道你的一些事情:)。

function loadData(data) {
    var view = new entryView(data);
    var groupName = data.name;
    $("#groupName").attr('id').empty();
    // error - typeerror $(...).attr(...) is undefined jquery
    alert($('#groupName').attr('id'));
}

entryView(data) {
    this.name = this.data.name
}

我不断收到TypeError: $(...).attr(...) is undefined。有人可以告诉我问题是什么吗?我的 jQuery 在下面。谢谢。

【问题讨论】:

  • 你用的是什么浏览器?
  • 您尝试在字符串上调用 empty() 方法,这就是您收到错误的原因
  • 这一行是否运行 alert($('#groupName').attr('id'));如果你放在错误行之前?以及它在警报中显示的内容?
  • 试试这个怎么样:$("#"+groupName).attr('id','');
  • 或 $("#"+data.name).empty()

标签: jquery ajax


【解决方案1】:

试试这个怎么样:

$("#"+groupName).attr('id','');

【讨论】:

    【解决方案2】:

    undefined 表示它找不到任何与您选择的元素匹配的选择器。这是因为groupName 是一个变量,您不能将它放在双引号内,因为它会将groupName 更改为String 而不是a变量。

    从以下位置更改您的代码:

    $("#groupName").attr('id').empty();
    

    进入这个:

    $("#"+groupName).attr('id','');
    

    如果您使用 jQuery 1.6 或更高版本,请像这样使用.prop()

    $("#"+groupName).prop('id','');
    

    【讨论】:

    • document.getElementById(groupName).innerHTML = "";
    【解决方案3】:

    没有 html 很难猜出你的意思,我猜你也有 X/Y 问题

    如果我猜你想要的话

    $("#*+groupName).empty();
    

    这将清空 ID 等于 groupName 的容器

    或者只是

    $("#*+groupName).html(data.content);
    

    替换内容

    【讨论】:

      【解决方案4】:

      如果你选择一个具有特定 ID 的元素,你不需要 jQuery:

      function loadData(data) {
          var view = new entryView(data); // I have no idea what this supposed to be doing.
      
          var groupName = data.name;
          var element = document.getElementById(groupName);
          alert(element.id);
          element.id = ""; // you can use this as a normal property, no "attr" magic
          alert(element.id);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-31
        • 2013-09-11
        • 1970-01-01
        • 1970-01-01
        • 2016-08-15
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        相关资源
        最近更新 更多