【问题标题】:JavaScript: onclick function to change another elements onclickJavaScript:onclick 函数来改变另一个元素 onclick
【发布时间】:2021-10-31 14:43:18
【问题描述】:

预期功能

我正在寻找这样运行的东西:

  1. 用户点击图片
  2. handclick 函数被调用并“启用”img 的父锚点
  3. 如果再次点击,锚点会将用户重定向到新页面

我的问题:

下面确实“启用”了链接,但它的作用就像链接被同时点击一样。

有没有办法修复这个功能?

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 代码

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

【问题讨论】:

    标签: javascript html function onclick


    【解决方案1】:

    由于我不知道不相关的代码是什么,我将只讨论第一次点击启用问题。

    我的方法包括href 属性。没有它,链接不起作用。所以,我所做的是将属性的名称更改为其他名称,然后在单击时将其替换为实际属性,从而“激活”链接。

    请注意,第一次单击后光标变为指针。

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 2021-02-02
      • 2015-08-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      相关资源
      最近更新 更多