I have two buttons:
<a href="#" id="A">Button-A</a>
<a href="#" id="B">Button-B</a>
And some JavaScript to trigger a click event:
jQuery("#A").click(function() {
jQuery("#B").trigger('click');
return false;
});
If Button-B
is not available (for example, on mobile, the button is not available), then Button-A
redirects user to a different page ( site.com/another-page
). How can I implement this?
How can I achieve that?
Thanks
You can check the length of the jQuery object to see whether it exists
jQuery("#A").click(function () {
var $btn = jQuery("#B").trigger('click');
if(!$btn.length){
window.location = 'new location'
}
return false;
});
Check if the element exists and then add the event listener
$(function(){
if($("#B").length) { // the element exists
jQuery("#A").click(function(){
jQuery("#B").trigger('click');
return false;
});
} else { // element doesn't exist, add a different listener
jQuery("#A").click(function(){
window.location = "http://newurl.com";
});
}
});
function clickHandler(e){
var $btn = $("#B").trigger('click');
if(!$btn.length)
window.location = 'site.com/another-page';
e.preventDefault();
}
$("#A").click(clickHandler);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.