简体   繁体   English

JavaScript:onclick 函数更改另一个元素 onclick

[英]JavaScript: onclick function to change another elements onclick

Intended Functionality预期功能

I'm looking for something that operates like this:我正在寻找像这样操作的东西:

  1. User clicks on the img用户点击 img
  2. handclick function gets called and 'enables' the parent anchor of the img handclick 函数被调用并“启用” img 的父锚点
  3. If clicked again, the anchor will redirect the user to a new page如果再次点击,锚点会将用户重定向到新页面

My Issue:我的问题:

The below does 'enable' the link, but it also acts as if the link was clicked at the same time.下面确实“启用”了链接,但它也表现为链接被同时点击。

Is there any way to fix this functionality?有没有办法修复这个功能?

HTML Code: HTML代码:

<a href="@Url.Action("Index/" + @card.ID)" onclick="return false;" class="link">
    <img src="~/Resources/@card.Image" id="@card.ID" onclick="handClick(@((int)card.Value), @card.ID)" class="card" />
</a>

JavaScript Code JavaScript 代码

function handClick(cardValue, cardID) {
    *... irrelevant code ...*
    var playedCard = document.getElementById(cardID);
    *... irrelevant code ...*
    playedCard.parentElement.onclick = function () { return true };
}

Since I don't know what the irrelevant code is I'll stay only on the first click enable issue.由于我不知道不相关的代码是什么,所以我只会停留在第一次点击启用问题上。

My approach includes the href attribute.我的方法包括href属性。 without it the link doesn't work.没有它,链接不起作用。 So, what I did was change the attribute's name into something else and when clicked, replace it with the actual attribute, thus "activating" the link.因此,我所做的是将属性名称更改为其他名称,并在单击时将其替换为实际属性,从而“激活”链接。

Notice that the cursor changes into a pointer after the first click.请注意,第一次单击后,光标会变为指针。

 document.querySelectorAll('a[hrefx]').forEach(function(el) { el.addEventListener('click', function() { // This condition enable re-using the listener for other purposes. if (this.getAttribute('hrefx')) { this.setAttribute('href', this.getAttribute('hrefx')); this.removeAttribute('hrefx'); } }); });
 <a hrefx="#"> <img src="https://picsum.photos/200"> </a> <a hrefx="#"> <img src="https://picsum.photos/200"> </a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM