calling .trigger(“click”) that is in javascript code returned from an ajax call

风格不统一 提交于 2019-12-25 02:01:31

问题


What i would like to do is trigger a button's click event from within a view that gets returned from an ajax call. This process works fine in a pc browser such as chrome but not so in a mobile browser. (i am using both jquery and jquery mobile).

(there is a lot more code involved in this but i have removed it for clarity)

I have a button in my html page like so.

 <input type="button" id="bt1" value=""  />

It has an onclick event listener on it defined somewhere else.

I have an ajax call that calls a php script like so:

 $.ajax({
        url: 'blah.php',
        type: 'get',
        data: {
            id : $('#field').val()
        },
        dataType: 'html',
        success: function (data) {
           $('#somediv').html(data);
        }
    });

It returns "data" which is a segment of html with inline javascript. It containts the following code:

<div>
<script type="text/javascript">
    $(document).ready(function () {
      $("#bt1").trigger("click");
     });
</script>
</div>

What ive noticed is that the trigger event will not be fired when used in a mobile. but works fine in pc.

Is there a different in the DOM when dealing with mobile that it prevents a trigger("click") from working if the object is outside the view?


回答1:


Try adding the touchstart event along side the click event.

$("#bt1").trigger("touchstart click");



回答2:


you may need to implement touch events on mobile. Take a look at this SO answer:

Understanding touch events

If you cannot change what comes back from the server then you can listen for a click event and trigger a touch event.

Good luck, Mike




回答3:


It cannot find the button since the javascript code and the button element is being created programatically, try:

$(document).find('#bt1').trigger('click');

or

$(document).find('#bt1').each(function(e) {
    e.trigger('click');
}

or, better:

success: function (data) {
    $('#somediv').html(data).promise().done(){
       $('#bt1').trigger('click');
    });
}


来源:https://stackoverflow.com/questions/29157206/calling-triggerclick-that-is-in-javascript-code-returned-from-an-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!