我可以将HTML元素绑定到js函数吗(而不是其他方式)

Can I bind an HTML element to a js function (rather than other way around)?

本文关键字:其他 方式 函数 HTML 元素 绑定 js 我可以      更新时间:2023-09-26

使用jQuery,我可以在HTML 中执行类似操作

<button id="click_me" type="button">Hello</button>

这个在js 中

$('#click_me').on('click', function() {alert('Hello')});

但我想以另一种方式进行关联。例如,HTML 中的类似内容

<button function="click_me" type="button">Hello</button>

这个在js 中

function click_me() {alert('Hello')};

有没有任何本地方法可以做到这一点,或者有一个库/框架可以做到(我只知道一点点jQuery(?将参数传入click_me怎么样?如果click_me是其他名称空间的成员(即click_me不是全局名称(,我该如何告诉HTML这个名称空间?如果我以jQuery的方式进行操作,那么我最终会得到与之一样多的事件侦听器吗?(我会有很多事件监听器,如果使用jQuery,我更喜欢事件委派(

您可以使用所谓的"传统事件注册",这就是@user3218194评论和Tsalikidis的回答。但在现代web开发中不建议使用它,因为它混合了页面的表示和逻辑,并且在过去造成了很多维护问题(更不用说无法为相同的事件类型注册更多的事件侦听器(。

如果您真的无法忍受注册侦听器,请使用事件委派:

<button data-behavior="click_me" type="button"></button>

jQuery:

$(document).on("click", "button[data-behavior='click_me']", function() {
    // Note: when using event delegation in jQuery, the keyword 'this' refers to the
    // target element, not the element 'on' has been called on (document in this case)
    alert("Hello, " + this.tagName); // should alert "Hello, BUTTON"
});

如果一次性执行此操作,即使是新添加的带有data-behavior="click_me"的按钮也会触发事件侦听器。

通过这种方式,您为元素附加了一个语义属性,然后由脚本进行管理。

<button onclick="javascript: click_me()"></button>
<script>
    function click_me() { }
</script>
  • 实时预览