Using jQuery, I'm simply trying to get the href
of the a
when the mouse clicks the image or the surrounding area.
HTML template:
<nav id="main_nav">
<ul>
<li>
<a href="/" data-path>
<img class="dashboard_icon" src="img/icons/nav/dashboard.svg">
</a>
</li>
</ul>
... more nav options
</nav>
Styles:
li { list-style: none; display: block; width: 80px; height: 80px; }
a { display: block; width: 100%; height: 100%; }
img { width: 30px; height: 30px; margin: 25px; }
jQuery:
$(document).on('click', '[data-path]', (e) => {
e.preventDefault();
let target = $(e.target).attr('href');
router.navigate(target);
});
But the problem is, whenever I click on the image inside the a
, I don't get the href
, as it tries to get the href
value from the image that I clicked on and not the a
. However, if I click on the area surrounding the image, I get the href
as desired.
Attempts:
I changed:
let target = $(e.target).attr('href');
To:
let target = $(this).attr('href');
But get absolutely nothing when clicking the image or the surrounding area!
What am I doing wrong? I can't believe I'm asking questions about simple things like this but I've just taken a year off coding and I'm obviously missing something important, and it's baffling me.
I want to be able to click everything inside the a
and get the href
of the a
.
您可以尝试e.currentTarget ,这将获取事件绑定到的元素, e.target 将获取实际单击的元素。
This might get you started:
$(document).on('click', '#main_nav a', function(e) {
e.preventDefault();
let target = $(this).attr('href');
alert(target)
});
See jsFiddle Demo
Using jquery it should be:
$(this).parent().attr('href');
Without using jquery this would be:
this.parentNode.getAttribute("href")
Complete code is:
$(document).on('click', 'image-class/id', (e) => {
e.preventDefault();
let target = $(this).parent().attr('href');
router.navigate(target);
});
Image is child of anchor tag, you need to get his parent when you click on image so this done by this way.
尝试: var href = event.toElement.parentElement.href;
Your issue is coming from the use of an arrow function instead of function(e)
Change (e) => {
to function(e) {
and use $(this).attr('href')
Quoting from mozilla -
An arrow function expression has a shorter syntax than a function expression and does not have its own this
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.