设置 JavaScript“this”单击时指向某个元素

发布于 2024-12-07 04:18:02 字数 416 浏览 1 评论 0原文

我正在寻找一种类似于 jQuery 的 .attr() 方法,当我单击一个元素(在本例中为 li 标签)时,我可以获得标签属性。

所以我的问题是,如何创建一个函数,当单击 li 时,函数中的 this 变量等于该 DOM 元素。我试图在不使用 jQuery 的情况下做到这一点。

这就是我认为可行但行不通的方法:

function selected(){
    this.title = this.getAttribute("title");
}

假设有一个带有属性 title 的元素 li 和一个带有函数 selected() 的 onclick作为选择。

I am looking for a way similar to jQuery's .attr() method, where when I click on an element (a li tag in this case) I can get the tags attributes.

So my question is, how can I make a function that when an li is click, the this variable in the function is equal to that DOM element. I am trying to do this without the use of jQuery.

This is what I have that I was thinking would work but it doesn't:

function selected(){
    this.title = this.getAttribute("title");
}

Assuming there is an element li with the attribute title and an onclick with the function selected() as the choice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

留蓝 2024-12-14 04:18:02

在 JavaScript 中,this 的值根据函数的调用方式而变化。基本上有 3 种调用模式:

  • 使用 new 运算符,例如 new Foo()。在这种情况下,当执行 Foo 时,this 指的是正在创建的新对象。
  • 取消引用对象上的方法,例如 foo.bar()。在这种情况下,当执行 bar 时,this 引用 foo。当一个方法没有从另一个对象取消引用时,例如,当仅调用全局方法时,this 引用全局范围或全局对象。
  • 使用applycall,例如foo.apply(bar)。通过使用callapply,您可以告诉解释器在调用期间this应该引用什么。
  • 作为一种特殊情况,this 指的是事件处理程序的节点。

在您的情况下,如果您有一个名为 selected 的全局函数,该函数是从事件处理程序调用的,如下所示:

<li onclick="selected()">

然后在调用 selected 期间,因为它没有取消引用从任何地方 this 都将引用全局对象。如果您希望 this 引用其事件处理程序正在触发的对象,那么您需要使用 callapply< 调用 selected /code> 模式并传递值 this (将引用该节点)作为上下文参数。

<li onclick="selected.call(this)">

我通常会尽量避免使用 callapply,因为通过查看 this 所引用的函数并不明显。因此,在这种情况下,我建议将节点作为参数传递。

<script>
    ...
    function selected(node) {
       node.title = node.getAttribute('title');
    }
</script>
...
<li onclick="selected(this)">

话虽如此,您的 selected 函数的实现并没有多大意义,因为它本质上是一个空操作(在许多情况下)。

In JavaScript, the value of this varies based on how a function is invoked. There are basically 3 patterns of invocation:

  • Using the new operator e.g. new Foo(). In this case when Foo is being executed this refers to the new object that is being created.
  • Dereferencing a method on an object e.g. foo.bar(). In this case when bar is being executed this refers to foo. When a method isn't dereferenced from another object, for example when just invoking a global method, the this refers to the global scope, or global object.
  • Using apply or call e.g. foo.apply(bar). By using call or apply you can tell the interpreter what this should refer to during an invocation.
  • As a somewhat special case, this refers to the node for event handlers.

In your case if you have a global function called selected that is invoked from an event handler such as the following:

<li onclick="selected()">

then during the invocation of selected, since it wasn't dereferenced from anywhere this will refer to the global object. If you want this to refer to the object whose event handler is firing then you need to invoke selected using the call or apply pattern and pass the value this (which will refer to the node) in as the context parameter.

<li onclick="selected.call(this)">

I usually try to shy away from using the call or apply since it isn't obvious from looking at the function what this will refer to. Therefore, in this case I would suggest passing in the node as a parameter.

<script>
    ...
    function selected(node) {
       node.title = node.getAttribute('title');
    }
</script>
...
<li onclick="selected(this)">

With all this being said, the implementation of your selected function doesn't make a ton of sense since it is essentially a no-op (in many cases).

蓝戈者 2024-12-14 04:18:02

这是一个令人困惑的问题,但类似:

$this = event.target;
$this.title = $this.getAttribute("title") || $this['title'];

可能有效,但请检查 this 是否引用了该元素。

This is a confusing question, but something like:

$this = event.target;
$this.title = $this.getAttribute("title") || $this['title'];

might work, but check that this is referencing the element.

泡沫很甜 2024-12-14 04:18:02

我可以建议以下内容:

document.onclick = function(e){
    if (e.target.tagName.toLowerCase() == 'li'){
        alert(e.target.title);
    }
};

JS Fiddle 演示

May I suggest the following:

document.onclick = function(e){
    if (e.target.tagName.toLowerCase() == 'li'){
        alert(e.target.title);
    }
};

JS Fiddle demo.

苯莒 2024-12-14 04:18:02
<script>
    function itemSelected(listItem)
    {
        // listItem is your HTMLLIElement
        alert(listItem.title);
    }
</script>
<ul>
    <li title="test1" onclick="itemSelected(this);">Test 1</li>
    <li title="test2" onclick="itemSelected(this);">Test 2</li>
</ul>
<script>
    function itemSelected(listItem)
    {
        // listItem is your HTMLLIElement
        alert(listItem.title);
    }
</script>
<ul>
    <li title="test1" onclick="itemSelected(this);">Test 1</li>
    <li title="test2" onclick="itemSelected(this);">Test 2</li>
</ul>
乙白 2024-12-14 04:18:02

如果您内联分配 onclick(在 html 内),那么您需要像这样处理它。

HTML

<li onclick="selected(this)">Click Me</li>

Javascript

function selected(element){
    alert(element.title);
}

如果您从 JavaScript 分配 onclick,那么这将起作用:

HTML

<li id="myli">Click Me</li>

Javascript

function selected(){
    alert(this.title);
}
document.getElementById("myli").onclick = selected;

If you assign the onclick in-line (inside the html), then you would need to handle it like this.

HTML

<li onclick="selected(this)">Click Me</li>

Javascript

function selected(element){
    alert(element.title);
}

If you assign the onclick from JavaScript then this will work:

HTML

<li id="myli">Click Me</li>

Javascript

function selected(){
    alert(this.title);
}
document.getElementById("myli").onclick = selected;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文