如何在触发 onclick 时从 Javascript 中的元素检索信息
How to retrieve information from an element in Javascript when onclick is triggered
假设我的 DOM 中有一个 link(但任何元素都可以接受),并调用 Javascript 功能:
<a href="google.com" onclick="myFunction()">
,以及一个 Jquery 函数来替换 link 上的点击并检索其 href
属性 (抱歉,我正在 Jquery, 但请随意用 vanilla JS 回答) :
function myFunction() {
$(this).click(function() { return false; }); // Cancel normal behavior.
console.log($(this).attr("href"));
}
这实际上行不通。通常,我们需要指向到一个元素的ID或Class来获取它的信息; 但是如果我们不能设置一个ID或者Class什么的,只是处理页面中的一些link,如何直接检索他们的信息 ?
本主题的标题有意笼统,因为该方法应该适用于任何 HTML 元素。
您可以访问如下点击的元素
<a href="https://google.com" onclick="myFunction(this)">
function myFunction(that) {
console.log(that.href);
}
HTML <a href="#" onclick="myFunction(event)">click</a>
JS
function myFunction(event) {
event.preventDefault();
// Do your stuff with event.target which is <a>
}
是的,你是对的,你可以使用 id 或 css 选择器。但还有另一种方法。
只需在调用函数时传递 this 即可访问元素的所有属性,如下所示:
<a href="google.com" style="background-color: yellow" onclick="myFunction(this, event)"> click me !!!! <a>
然后您可以访问如下所有信息:
function myFunction(element, event) {
event.preventDefault(); // event object can be passed
element.style.backgroundColor = "red" // attribute can be accessed
console.log(element.attributes["data-name"])
}
假设我的 DOM 中有一个 link(但任何元素都可以接受),并调用 Javascript 功能:
<a href="google.com" onclick="myFunction()">
,以及一个 Jquery 函数来替换 link 上的点击并检索其 href
属性 (抱歉,我正在 Jquery, 但请随意用 vanilla JS 回答) :
function myFunction() {
$(this).click(function() { return false; }); // Cancel normal behavior.
console.log($(this).attr("href"));
}
这实际上行不通。通常,我们需要指向到一个元素的ID或Class来获取它的信息; 但是如果我们不能设置一个ID或者Class什么的,只是处理页面中的一些link,如何直接检索他们的信息 ?
本主题的标题有意笼统,因为该方法应该适用于任何 HTML 元素。
您可以访问如下点击的元素
<a href="https://google.com" onclick="myFunction(this)">
function myFunction(that) {
console.log(that.href);
}
HTML <a href="#" onclick="myFunction(event)">click</a>
JS
function myFunction(event) {
event.preventDefault();
// Do your stuff with event.target which is <a>
}
是的,你是对的,你可以使用 id 或 css 选择器。但还有另一种方法。
只需在调用函数时传递 this 即可访问元素的所有属性,如下所示:
<a href="google.com" style="background-color: yellow" onclick="myFunction(this, event)"> click me !!!! <a>
然后您可以访问如下所有信息:
function myFunction(element, event) {
event.preventDefault(); // event object can be passed
element.style.backgroundColor = "red" // attribute can be accessed
console.log(element.attributes["data-name"])
}