Two ways to make a clickable button:

Method 1:

<img src="image.png" alt="" id="btn_img" />

Method 2:

<a id="btn_img"><img src="image.png" alt="" /></a>

Apart from CSS rendering difference (e.g. the cursor, the blue image border produced by IE), if I assign a click event to the id btn_img, is there any behavioral difference, e.g. cross-browser compatibility? and the most important question, which method is preferred?

The code to add event:

$('#btn_img').click(function() {
  alert('do something');
});

hope this question won't fall into "opinion-based" category.

有帮助吗?

解决方案

Both results are the same. The only difference is that the click event is triggered in the image in the first method and in the link tag in second method. So we need to prevent the default behavior of the a tag but not the img tag. Anyway, in regards to styling purposes, wrapping the img tag with any element would be better than that not wrapping it, so it's better practice to use the second method.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top