问题
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