Javascript div点击调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2424195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call function on div click
提问by luke
I am doing this: <div onclick='alert("xxx")'>Click me!</div>and i see that alert but i want to call on function inside that onclick.
I'm trying this but it doesn't work.
我正在这样做:<div onclick='alert("xxx")'>Click me!</div>我看到了那个警报,但我想调用 onclick 中的函数。我正在尝试这个,但它不起作用。
function GetContent(prm){
alert(prm);
}
<div onclick='GetContent("xxx")'>Click me!</div>
I need to call that function inline not assign an id or class to that div and use jquery.What is the solution? Thanks
我需要内联调用该函数,而不是为该 div 分配 id 或类并使用 jquery。解决办法是什么?谢谢
回答by Sarfraz
Using code inlineis bad practice, you need to assign an IDor Classto the div and call function against it eg:
使用代码inline是不好的做法,您需要为div分配一个IDorClass并针对它调用函数,例如:
<div class="test">Click me!</div>
$('div.test').click(function(){
GetContent("xxx");
});
.
.
I need to call that function inline not assign an id or class to that div and use jquery.
我需要内联调用该函数,而不是为该 div 分配 id 或类并使用 jquery。
I think you are already doing that with this code:
我认为您已经使用此代码执行此操作:
<div onclick='GetContent("xxx")'>Click me!</div>
Calling function inline without assigning id or class. But as said before, it is not good practice to use inline code.
内联调用函数而不分配 id 或 class。但如前所述,使用内联代码并不是一个好习惯。
回答by rahul
You can give that div a class and then do something like this
你可以给那个 div 一个类,然后做这样的事情
$("div.myclass").click(function(){
GetContent("xxx");
});
<div class="myclass"></div>
This will fire click event to all div elements with class 'myclass'.
这将向所有具有“myclass”类的 div 元素触发点击事件。
But I am not sure why you don't want to give an id to the div element.
但我不确定为什么你不想给 div 元素一个 id。

