Javascript-将单击的对象作为 onClick 函数中的参数发送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17753719/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:29:12  来源:igfitidea点击:

Javascript- send the clicked object as parameter in onClick function

javascriptjqueryhtml

提问by Aman Gupta

In function clickCircle, i want to use the li which is being clicked. So i want to receive it as a parameter.

在函数 clickCircle 中,我想使用被点击的 li。所以我想将它作为参数接收。

<li class="circle" onClick='clickCircle(this)'></li>

But what should i send as an actual paramenter? ie in place of 'this'.

但是我应该发送什么作为实际参数?即代替“这个”。

回答by pala?н

You can use this:

您可以使用this

function clickCircle(obj) // the li element clicked in the current scope
{
    var element = obj;  // This is the DOM object being clicked
    var $this = $(obj); // This is the jQuery object being clicked

    // Use DOM object like
    element.style.color="#ff0000";

    // Use jQuery object like 
    $this.css('color', 'red');
}

回答by intuitivepixel

Try this instead

试试这个

<li class="circle"></li>

$('.circle').on('click', function(event) {
  event.target // your element
});

回答by edi9999

You should just use the first parameter as the element.

您应该只使用第一个参数作为元素。

HTML

HTML

<li class="circle" onClick='clickCircle(this)'></li>

JS

JS

clickCircle=function(element)
{
console.log(element)
console.log(element.tagName) // This will show LI
}

JSFiddle: http://jsfiddle.net/edi9999/WhVLm/

JSFiddle:http: //jsfiddle.net/edi9999/WhVLm/

回答by Bounasser Abdelwahab

you can do it with jquery like this:

你可以用 jquery 来做到这一点:

$(function () {
  $('li.circle').on('click', function () {
    clickCircle($(this));
  });
});

var clickCircle = function (param) {
  // your code here
  // param.css('color', 'red').html();
};

or with raw javascript:

或使用原始 javascript:

HTML

HTML

<li id="circle" class="circle"></li>

JAVASCRIPT

爪哇脚本

var circle = document.getElementById('circle');

circle.addEventListener('click', function (e) {
  clickCircle(e.target);
});

var clickCircle = function (param) {
  // your code here
  // alert(param.nodeName.toLowerCase());
}