如何在jquery中将变量指定为div名称

时间:2014-08-04 07:32:57

标签: jquery ajax

点击链接时,我会调用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在下面。谢谢。

4 个答案:

答案 0 :(得分:0)

尝试这个怎么样:

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

答案 1 :(得分:0)

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

更改您的代码:

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

进入这个:

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

如果您使用的是jQuery 1.6或更高版本,请使用.prop(),如下所示:

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

答案 2 :(得分:0)

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

如果我猜你想要

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

将清空ID等于groupName的容器

或只是

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

将替换内容

答案 3 :(得分:0)

如果您选择具有特定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);
}