使用“javascript:”URL将“this”元素传递给JS函数

时间:2022-02-08 15:12:08

In short, I want to do

总之,我想做

<a href="javascript:edit(this, 123)">Edit thing</a>

instead of

<a href="javascript:;" onclick="edit(this, 123)">Edit thing</a>

where this would be the <a />, and 123 is an id. Why? It's much cleaner. Is there any way?

这将是,123是一个id。为什么?它更清洁。有什么办法吗?

1 个解决方案

#1


9  

How about we keep things semantic?

我们如何保持语义?

<button type="button" id="edit"> Edit this </button>

and then add some javascript somewhere

然后在某处添加一些javascript

document.getElementById("edit").addEventListener("click", function(ev) {
  // do edit logic
}, false);

You'll have issues with addEventListener in legacy browsers. Feel free to use flow to fix addEventListener

您将在旧版浏览器中遇到addEventListener问题。随意使用流来修复addEventListener

I also recommend you read about

我也建议你阅读一下

And choose one of those two techniques.

并选择这两种技术中的一种。

Also please don't hard code id's into your functions like that. Your edit button should know what it's editing by relative position in the DOM. it should be easy to find the semantic id that is on the correct element by a simple bit of DOM traversal.

另外,请不要将id硬编码到你的功能中。您的编辑按钮应该知道它在DOM中的相对位置进行编辑。通过简单的DOM遍历可以很容易地找到正确元素上的语义ID。

#1


9  

How about we keep things semantic?

我们如何保持语义?

<button type="button" id="edit"> Edit this </button>

and then add some javascript somewhere

然后在某处添加一些javascript

document.getElementById("edit").addEventListener("click", function(ev) {
  // do edit logic
}, false);

You'll have issues with addEventListener in legacy browsers. Feel free to use flow to fix addEventListener

您将在旧版浏览器中遇到addEventListener问题。随意使用流来修复addEventListener

I also recommend you read about

我也建议你阅读一下

And choose one of those two techniques.

并选择这两种技术中的一种。

Also please don't hard code id's into your functions like that. Your edit button should know what it's editing by relative position in the DOM. it should be easy to find the semantic id that is on the correct element by a simple bit of DOM traversal.

另外,请不要将id硬编码到你的功能中。您的编辑按钮应该知道它在DOM中的相对位置进行编辑。通过简单的DOM遍历可以很容易地找到正确元素上的语义ID。