如何添加内联jquery事件

时间:2011-06-06 11:47:21

标签: jquery events inline

我希望以这种方式添加像mouseenter这样的jQuery事件,如

ImageTag mouseenter="callSomefunction" id="imgId"

而不是

ImageTag onmouseover="callSomefunction" id="imgId"

我该怎么做?

2 个答案:

答案 0 :(得分:2)

jQuery不能将标记用作属性。

您需要使用javascript找到该元素,因此在javascript块中您将找到该元素,然后您将能够绑定一个事件:

<script>
    $("#imgId").mouseenter(function() { /* your stuff */ });
</script>

此脚本块必须在元素之后执行,因为在尝试获取元素之前必须存在该元素。

在尝试任何事情之前,您应该阅读有关jQuery的更多信息,http://jquery.com/

答案 1 :(得分:0)

然而,没有什么可以阻止你在标记中添加你想要的东西了:

  1. 这会产生无效的标记。
  2. 它不起作用,因为mouseenter不是标签的有效属性。
  3. 回答你的问题:

    <img id="imgId" mouseenter="callSomefunction" />
    

    我不推荐这种方法。