使用jquery隐藏动态创建的元素

时间:2013-01-07 10:43:19

标签: javascript jquery html

我通过ajax获取数据。我有一个包含所有数据的数组。现在我在数组中运行一个循环并动态创建一个对应于数组每个元素的'p'和'button'。如果我点击按钮,相应'p'的innerHTML应传递给ajax,按钮必须消失。这是我试过的样本:

<script>
for(var i=0;i<foo.length;i++)
{
     addElement(foo[i],i);
}
function addElement(foo,i)
{
    ni=document.getElementById("asdf");
    new_but=document.createElement('input');
    new_p=document.createElement('p');
    new_p.id='text'+toString(i);
    new_p.innerHTML=foo;
    new_but.type='button';
    new_but.value='add';
    new_but.id=toString(i);
    new_but.className='but';
    ni.appendChild(new_p);
    ni.appendChild(new_but);
}
$(document).ready(function(){
    $('.but').each(function(){
        $(this).click(function(){
            $.ajax({
              type:'POST',
              data:'awdwad',
              url:'aadwewq.php',
              success:function(result)
              {
                  if(result==no_error)
                  $(this).hide();
              }
});});});});
</script>

创建了元素,但我以后无法使用带有jquery的id或类来访问它们。

4 个答案:

答案 0 :(得分:4)

问题是因为当click元素不存在时,.but处理程序被分配onload。您需要将click处理程序委托给父元素,如下所示:

$(document).ready(function(){
    $('#asdf').on('click', '.but', function(){
        $.ajax({
            type:'POST',
            data:'awdwad',
            url:'aadwewq.php',
            success:function(result) {
                if (result == no_error)
                    $(this).hide();
            }
        });
    });
});

此外,您可以使用jQuery缩短addElement函数:

function addElement(foo, i) {
    var $ni = $('#asdf');
    var $p = $('<p></p>', { 'id', 'text' + toString(i) }).html(foo).appendTo($ni);
    var $button = $('<input></input>', {
        'type': 'button',
        'id': toString(i),
        'class': 'but'
    }).appendTo($ni);
}

答案 1 :(得分:2)

使用.on并在某些父对象或文档上附加事件。此外,无需迭代对象。

$(document).on("click", ".but", function(){
});

答案 2 :(得分:0)

this来电的success回调中的

$.ajax是指ajax通话本身。 您应首先引用该按钮。

结合其他答案的反馈:

$(function() {
    $(document).on('click', '.but', function() {
       var btn = $(this);
       $.ajax({
           type:'POST',
           data:'awdwad',
           url:'aadwewq.php',
           success:function(result)
           {
               if(result==no_error)
               $(btn).hide();
           }
       });
    });
});

答案 3 :(得分:0)

function addElement(foo,i){
    ni=document.getElementById("asdf");
    new_but=document.createElement('input');
    new_p=document.createElement('p');
    new_p.id='text'+i; //remove toString
    new_p.innerHTML=foo;
    new_but.type='button';
    new_but.value='add';
    new_but.id=i;  // remove toString
    new_but.className='but';
    ni.appendChild(new_p);
    ni.appendChild(new_but);
}
相关问题