doufu6423
2013-04-20 03:17
浏览 47
已采纳

jQuery没有处理由jQuery创建的元素

I am dynamically adding list items to a list in jQuery through an ajax call that is called every second.

Below is the code for the ajax call.

$.ajax({
    url: 'php/update_group_list.php',
    data: '', 
    dataType: 'json',
    success: function(data) {
        var id = data.instructor_id;
            group_cnt = data.group_cnt,
            group_name = data.group_name,
            group_code = data.group_code;

            for (i = current_row; i < group_cnt; i++)
            {
                //setInterval(function() { $('#group-list-div').load('php/group_list.php'); }, 5000);

                $('#group-list').append("<li><a href='#' data-role='button' class='view-group-btns' id='"+group_code[i]+"' value='"+id+"' text='"+group_name[i]+"'>"+group_name[i]+"</a></li>");
                $('#delete-group-list').append("<fieldset data-role='controlgroup data-iconpos='right'>" +
                                                    "<input id='"+group_code[i]+i+"' value='"+group_code[i]+"' type='checkbox' name='groups[]'>" +
                                                    "<label for='"+group_code[i]+i+"'>"+group_name[i]+"</label>" +
                                                "</fieldset>");
            }

            current_row = i; 

            $('#group-list').listview('refresh');
            $('#delete-group-list').trigger('create');
    }
});

Now I am having two problems

FIRST PROBLEM:

When I try to run the code below (it should show an alert box if any of the list items created in this line $('#group-list').blah...blah in the code above), nothing happens.

$(".view-group-btns").click(function() 
{
    alert("check");
});

SECOND PROBLEM:

Also when I try to send the form data for the checkboxes (referencing line $('#delete-group-list').blah...blah in the ajax call code above) the post returns the error unexpected token <

What am I doing wrong? I think the two problems are related as I am creating the list items that are used dynamically.


Here is extra code relating to the SECOND problem

HTML:

<form id='delete-group-form' action='php/delete_groups.php' method='post'>
    <h3 style='text-align: center;'>Check the Box Beside the Groups you Would Like to Delete </h3>
    <div style='margin-top: 20px;'></div>
        <div id='delete-group-list'>
        </div>
    <div style='margin-top: 20px;'></div>
    <input type='submit' id='delete-groups-btn' data-theme='b' value='Delete Groups(s)'>                    
</form>

JS Code

$('#delete-group-form').submit(function(e) 
{
    e.preventDefault();

    alert($('#delete-group-form').serialize());

    if ($('#delete-group-form').serialize() == "") 
    {
        alert('No groups selected to be deleted.')
        return false;
    }
    else 
        if ($('#delete-groups-form').serialize() == null) 
        {
            alert('No groups selected to be deleted.')
            return false;
        } 
        else 
        {
            $.post('php/delete_groups.php',$('#delete-groups-form').serialize()).done(function(data) 
            {
                obj = jQuery.parseJSON(data);


                var group_codes = obj.group_list;

                alert(group_codes);

                alert("The selected groups have been deleted");
                window.setTimeout(2000);
                return false;
            });
        }
    return false;
});

delete_groups.php

<?php 
    $group_codes = $_POST['groups'];    
    $items = array('group_list'=>$group_codes); //creating an array of data to be sent back to js file
    echo json_encode($items); //sending data back through json encoding
?>

I think the root of the SECOND problem is the line $group_codes = $_POST['groups']; specfically the $_POST['groups'] because when I replace it with $group_codes = 'test'; (just for debugging purposes) , the code works as expected.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dongyuying1507 2013-04-20 03:27
    已采纳

    You need to use event delegation to make your newly-created elements function properly:

    $("#group-list").on("click", ".view-group-btns", function() {
        alert("check");
    });
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duandao6414 2013-04-20 03:19

    You have to use the jquery on event.

    $(".view-group-btns").on("click", function(event)
    {
        alert("check");
    });
    

    Why?

    Because you can only use the regular "click" on elements that are created BEFORE the DOM is updated.

    When you are dynamically creating new elements into the dom tree, then you can't use .click anymore.

    on (and in the past, .live(), which is deprecated now) can listen to modifications in the DOM tree and can use the later-on created elements.

    评论
    解决 无用
    打赏 举报
  • dougaicha5258 2013-04-20 03:29

    I noticed you have 3 single quotes on this line... missed one after controlgroup

    $('#delete-group-list')."<fieldset data-role='controlgroup data-iconpos='right'>"
    

    That would explain the unexpected token <

    评论
    解决 无用
    打赏 举报
  • dop82210 2013-04-20 03:32

    You have to bind the click function after you get the element from ajax call. Binding on pageLoad event will only bind with those elements that are already in the dom. So do something like this.

    $.ajax({
    success : function(res){
    //bind your click function after you update your html dom.
    }
    })
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题