使用 Javascript 替换对象的 onclick 函数

Replace onclick function of an object using Javascript

如何在使用 onclick 时替换按钮上的目标 URL?

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

所以它看起来像这样

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

下面的 Javascript 代码不起作用。为什么?

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

一种简单的方法是添加侦听器并阻止事件的默认行为

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

working example

您在标签中使用的 onclick - 是 html 事件属性,但标签中的 onclick,您也试图更改 - 是 div 对象 属性.

两者都像“onclick”,但不一样。

所以,如果你想让事情顺利进行,请这样做:

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

onclick div 属性 需要函数(回调)而不是字符串

element.onclick 需要分配一个函数,不同于 <node onclick=""> 属性,其中内容将自动包装在一个函数中。

如果要更改属性,请使用element.setAttribute("onclick", "...");

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

行为类似于:

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

另一种解决方案是使用 data-attributes,可以通过 element.dataset.name 访问。

示例:

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

并更改它:

my_button.dataset.path = "/otherPath";