在.load()中传递变量

时间:2013-03-14 09:39:34

标签: jquery

我有一个页面,其中包含许多名为.comment_holder的div,每个div都包含不同的ID号,例如

<div class="comment_holder" id="123"></div>
<div class="comment_holder" id="345"></div>

我想将id传递到我正在加载的页面,该页面会在执行操作时附加.comment_holder div。以下是我正在尝试的内容:

$('.comment_holder').load('/pages/includes/wall.php', { 
    var wlid = $(this).attr("id");
    wl_id: wlid; 
});

但我明白了:SyntaxError: missing : after property id

我应该采取哪些不同的方式?

4 个答案:

答案 0 :(得分:3)

data参数不是正确的对象文字。 this也不在对象文字的范围内,因此遍历调用每个元素的加载函数的元素。使用传递给函数的元素来检索id。

$('.comment_holder').each(function(index, elem){
   $(elem).load('/pages/includes/wall.php', { 
        wl_id: $(elem).attr("id") 
    });
});

类似示例: http://jsfiddle.net/qQ4Np/1/

答案 1 :(得分:0)

$('.clicker').click( function(){ 
var myId = $(this).attr("id");

$('.comment_holder').load('/pages/includes/wall.php', { 
    myId: myId; 
});});

和wall.php:

$myId = $_POST['myId'];

答案 2 :(得分:0)

或者,如果您想在页面加载时动态加载数据,则必须在循环$ .each()中执行此操作

$('.comment_holder').each( function(){ 
    var myId = $(this).attr("id");
    $(this).load('/pages/includes/wall.php', { 
        myId: myId; 
    });
});

答案 3 :(得分:-1)

你不能在这样的对象文字中包含var语句。所以只需将id分配给对象属性

$('.comment_holder').load('/pages/includes/wall.php', { 
   wl_id: $("comment_holder").attr("id")
});

但是如果你有.comment_holder类的多个元素,那就行不通。所以我建议使用Kevin的方法并循环收集。

相关问题