JQuery: URL is opening twice - how to only open once?
I have a table in which the rows are clickable. Also within the row I have a clickable button. Both when clicked open a new window and the same URL. The clickable row is achieved by JQuery. The clickable button by HTML. (in case javascript disabled) How can I stop the URL opening twice ie when the button within the row is clicked? I have tried boolean logic but could not get it to work i.e the and button still need to be functional even after clicking the button once.
I am very new to Javascript and Jquery. Many Thanks. Pls find my code below:
Jquery code:
$(document).ready(function() {
$('#myTable tr').click(function() {
var href = $(this).find("a").attr("href");
if (href) {
window.open(href);
}
});
});
the HTML code:
<td>
<a href="some link" target="_blank">
<img src="image.jpg"/>
</a>
</td>
开发者_高级运维
event.preventDefault() will stop any default actions from being executed.
$(document).ready(function() {
$('#myTable tr').click(function(event) {
var href = $(this).find("a").attr("href");
if (href) {
window.open(href);
event.preventDefault();
}
});
});
Ok so, I took another look at this and realized the original nugget of advice was correct, but that the child link is the one that needs to have its default behavior prevented.
$(document).ready(function() {
$('#myTable tr td a').click(function(e) {
e.preventDefault();
});
$('#myTable tr').click(function() {
var href = $(this).find("a").attr("href");
if (href) {
window.open(href);
}
});
});
Looking back at the comments Usman suggested this.
精彩评论