Kon*_*nos 49 html javascript jquery
我需要在onclick事件的调用对象上有一个处理程序
即
<a href="123.com" onclick="click123(event);">link</a>
<script>
function click123(event)
{
//i need <a> so i can manipulate it with Jquery
}
</script>
Run Code Online (Sandbox Code Playgroud)
我想这样做而不使用$().click或$().live of jquery但是使用上述方法.
Rus*_*Cam 114
传入this内联单击处理程序
<a href="123.com" onclick="click123(this);">link</a>
Run Code Online (Sandbox Code Playgroud)
或event.target在函数中使用(根据W3C DOM Level 2事件模型)
function click123(event)
{
var a = event.target;
}
Run Code Online (Sandbox Code Playgroud)
但当然,IE是不同的,所以vanilla JavaScript处理这个问题的方法是
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
}
Run Code Online (Sandbox Code Playgroud)
或者更简洁
function doSomething(e) {
e = e || window.event;
var targ = e.target || e.srcElement;
if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
}
Run Code Online (Sandbox Code Playgroud)
其中e在event object被传递给函数在比IE其他浏览器.
如果您正在使用jQuery,我会强烈鼓励不引人注目的JavaScript并使用jQuery将事件处理程序绑定到元素.
最简单的方法是通过这个给click123功能,或者您也可以做这样的事情(跨浏览器):
function click123(e){
e = e || window.event;
var src = e.target || e.srcElement;
//src element is the eventsource
}
Run Code Online (Sandbox Code Playgroud)
你的方法的问题是你用 JavaScript 弄乱了你的 HTML。如果你把你的 JavaScript 放在一个外部文件中,你就可以不引人注目地访问你的 HTML,这要整洁得多。
稍后您可以使用 addEventListener/attackEvent(IE) 扩展代码以防止内存泄漏。
这是没有 jQuery 的情况
<a href="123.com" id="elementid">link</a>
window.onload = function () {
var el = document.getElementById('elementid');
el.onclick = function (e) {
var ev = e || window.event;
// here u can use this or el as the HTML node
}
}
Run Code Online (Sandbox Code Playgroud)
你说你想用 jQuery 来操作它。所以你可以使用 jQuery。比这样做更好:
// this is the window.onload startup of your JS as in my previous example. The difference is
// that you can add multiple onload functions
$(function () {
$('a#elementid').bind('click', function (e) {
// "this" points to the <a> element
// "e" points to the event object
});
});
Run Code Online (Sandbox Code Playgroud)
我认为最好的方法是使用currentTarget属性而不是target属性。
当事件遍历 DOM 时,Event 接口的 currentTarget 只读属性标识了 event的当前目标。它始终指的是事件处理程序已附加到的元素,而不是 Event.target,后者标识发生事件的元素。
例如:
<a href="#"><span class="icon"></span> blah blah</a>
Run Code Online (Sandbox Code Playgroud)
Javascript:
a.addEventListener('click', e => {
e.currentTarget; // always returns "a" element
e.target; // may return "a" or "span"
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
152402 次 |
| 最近记录: |