更改JQuery附加元素的值

时间:2012-11-22 08:27:25

标签: javascript jquery

所以我在页面上新添加了附加了Jquery.live()的元素,我现在想要在追加这些元素之后更改那些元素的值。

类似

   $("#questionForm").empty();
        $.get("questionCreator.html", function(data){
            $("#questionForm").append(data);

        });
        var index=$(this).parent().index();
        id = index; 
        var associatedQuestion = idQuestionAssociation[index];
        var associatedResponses = idResponsesAssociation[index];
        if(associatedQuestion != null){
            $(".questionInput").val(associatedQuestion);
        }

所以.val()调用,我认为不起作用,因为最初没有.questionInput元素,并且这是附加的。我觉得我应该使用.live,或.delegate,或.on,但我不确定我应该使用什么事件。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

$.get是异步的,这意味着您尝试与$(".questionInput")匹配的元素尚未在DOM中。您应该将其余的DOM操作放在回调中。

    $.get("questionCreator.html", function(data){
        $("#questionForm").append(data);
        //change the values here
    });

答案 1 :(得分:0)

尝试使用replaceWith更改内容,但调用$(".questionInput")可能会返回一个数组,因此最好循环遍历可能的元素 - 除非它是唯一的,然后将其设为id属性(#questionInput)无需循环即可调用它。

$('.questionInput').each(function(i, obj) {
    $(this).replaceWith('I am replacing the content for .questionInput');
});

这应该在返回数据后进入get函数。

相关问题