在内联事件处理程序中引用`this`

时间:2018-04-14 09:01:13

标签: javascript html

我希望能够通过这个'在javascript' mouseover'中。我基本上想从链接(这是唯一的)获取href并将其传递给每个下载按钮。但我收到错误消息:

  

undefined不是对象(评估' this.getElementsByClassName(' downLoad_link')[0] .href = x)

对此非常新,所以我希望有人能帮助我! :)

这是我的代码:

sudo aptitude install alien

修改

当我解决此问题时,

' www.example.com' 将被变量替换!

好的,我的新代码是这样的:

使用Javascript:

sudo apt-get install aptitude

HTML:

<a onmouseover="this.getElementsByClassName('downLoad_link')[0].href = 'www.example.com'" href="" class="downLoad_link" download>
    <button class="download">Download</button>
</a>

2 个答案:

答案 0 :(得分:2)

只使用this而不是this.getElementsByClassName('downLoad_link')[0]

&#13;
&#13;
<a onmouseover="this.href = 'www.example.com'" href="" class="downLoad_link" download>
  <button class="download">
    Download
    </button>
</a>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我认为这将回答你的第二个问题。

&#13;
&#13;
var x = document.getElementById('getDownloadLink').href; //this is not working!
&#13;
<a onmouseover="alert(x)" href="random" id="getDownloadLink">Download</a>
&#13;
&#13;
&#13;

这里href的值放在变量x中。作为一个例子,我现在将onmouseover更改为alert(x)。

相关问题