使用jquery .on()vs .click()

时间:2012-09-17 14:13:30

标签: jquery

我有一个播放流的网站。一旦有人按下按钮,我就会对服务器执行AJAX调用。

<input type="submit" class="play" data-type="<?php echo $result_cameras[$i]["camera_type"]; ?>" data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>" value="<?php echo $result_cameras[$i]["camera_name"]; ?>">

这会打印出一堆用户可以选择的按钮。这由以下代码处理:

<script>
$(document).ready(function(){

$(".play").on('click', function(){
    var camerahash = $(this).data('hash');
    var cameratype = $(this).data('type');
    function doAjax(){
        $.ajax({
            url: 'index.php?option=streaming&task=playstream&id_hash=<?php echo $id_hash; ?>&camera_hash='+camerahash+'&format=raw',
            success: function(data) {
                if (data == 'Initializing...please wait')
                {
                    $('#quote p').html(data); //shows a message here
                    setTimeout(doAjax, 2000);
                }
                else
                {
                    if (cameratype == "WEBCAM" && data == 'Stream is ready...')
                    {
                        $('#quote p').html(data); //another message here
                        window.location = 'rtsp://<?php echo DEVSTREAMWEB; ?>/<?php echo $session_id;?>/'+camerahash;
                    }
                    else if (cameratype == "AXIS" && data == 'Stream is ready...')
                    {
                        $('#quote p').html(data); //another message here
                        window.location = 'rtsp://<?php echo DEVSTREAMIP; ?>/<?php echo $session_id;?>/'+camerahash;
                    }
                    else
                    {
                        $('#quote p').html(data); //another message here
                    }

                }

            }
        });

    }
    doAjax();
});
});
</script>

当用户点击按钮时收到消息,一切正常。但是单击另一个按钮不再显示消息。我已经将委托事件(.on)用于动态加载的按钮(而不是.click()),我认为这会解决这个问题,但看起来我只是不知道我需要做什么。 / p>

3 个答案:

答案 0 :(得分:2)

尝试使用以下内容:

$(document).on("click", ".play", function() {
    // Data
}

答案 1 :(得分:2)

要开始,您需要在.on中指定一个选择器。在您的情况下,如果您没有父/祖先,您可以指定document

 $(document).on('click', '.play', function(){....

答案 2 :(得分:2)

绑定父元素并委托按钮。

例如,绑定在表上并绑定到'tr',因为绑定它时TR可能不存在。

$("#dataTable").on("click", "tr", function(event){ alert($(this).text()); });

你应该结账CanJS(canjs.us),他们有这种类型的自动绑定器。