简体   繁体   English

使用 Javascript 替换对象的 onclick 函数

[英]Replace onclick function of an object using Javascript

How do I replace the destination URL on a button when using onclick?使用 onclick 时如何替换按钮上的目标 URL?

<div id="my_button" onclick="window.location.replace('/destination1')">Button<div>

So it would look like this所以它看起来像这样

<div id="my_button" onclick="window.location.replace('/destination2')">Button<div>

The following Javascript code doesn't work though.以下 Javascript 代码不起作用。 Why?为什么?

<script>
document.getElementById("my_button").onclick="window.location.replace('/destination2')"
<script>

onclick that you have used in tag - is html event attribute, but onclick in tag, that you also tring to change - is div object property.您在标签中使用的 onclick - 是 html 事件属性,但标签中的 onclick,您也想更改 - 是 div 对象属性。

Both are like "onclick", but it's not the same.两者都像“onclick”,但并不相同。

So, if you want to make thing work, do this:因此,如果您想让事情正常进行,请执行以下操作:

document.getElementById("my_button").onclick = () => window.location.replace('/destination2');

onclick div property need function(callback) not a string onclick div 属性需要函数(回调)而不是字符串

A simple way to do it would be by adding a listener and preventing the default behavior of the event一个简单的方法是添加一个监听器并阻止事件的默认行为

document
  .getElementById('my_button')
  .addEventListener('click', function (event) {
    event.preventDefault();
    window.location.replace('/destination2');
  });

working example工作示例

element.onclick requires a function to be assigned and differs from the attribute <node onclick=""> where the content will be wrapped up in a function automatically. element.onclick需要分配一个函数,并且不同于属性<node onclick=""> ,其中内容将自动包装在一个函数中。

If you want to change the attribute, make use of element.setAttribute("onclick", "...");如果要更改属性,请使用element.setAttribute("onclick", "...");

element.setAttribute("onclick", "window.location.replace('/destination2');");

Behaves similar to:行为类似于:

element.onclick = function() { window.location.replace('/destination2'); };

Another solution would be using the data-attributes which can be accessed by element.dataset.name .另一种解决方案是使用可以通过element.dataset.name访问的数据属性

Example:例子:

<div id="my_button" data-path="/destination2" onclick="window.location.replace(this.dataset.path);">Button</div>

And to change it:并改变它:

my_button.dataset.path = "/otherPath";

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

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