jQuery 通过 event.target 我怎么知道它是复选框还是收音机?

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

by event.target how i know that it is checkbox or it is radio?

javascriptjquery

提问by Rituraj ratan

in my html

在我的 html 中

<input type="checkbox" name="select">

<input type="radio" name="select">

name property same due to some logical reason

由于某种逻辑原因,名称属性相同

in my JS

在我的 JS 中

i write below code

我写下面的代码

$('input[type="checkbox"],input[type="radio"]').on("change",function(event){
console.log(event.target.nodename);
// on both cases it show "INPUT"
}

}); 

Then how i will know that i click on checkbox or radio button

然后我怎么知道我点击了复选框或单选按钮

any help would be appreciated

任何帮助,将不胜感激

回答by Jai

.nodeNamegives the htmltag used so you have to use .typeto get the type of the node there.

.nodeName给出了html使用的标签,所以你必须使用它.type来获取节点的类型。

Try this one:

试试这个:

console.log(event.target.type);

Demo

演示

回答by Jamey

For those of you looking for the pure JavaScript way, it's event.target.tagName.

对于那些正在寻找纯 JavaScript 方式的人来说,它是event.target.tagName.

That property is an uppercase string of the element type, like "A", "UL", "LI", etc.

该属性是元素类型的大写字符串,如“A”、“UL”、“LI”等。

回答by Arun P Johny

console.log($(event.target).is(':radio'));
console.log($(event.target).is('[type="radio"]'));

回答by Rohan Kumar

Try to use attr()like,

尝试使用attr() 之类的,

console.log($(this).attr('type'));// checkbox or radio

Code

代码

$('input[type="checkbox"],input[type="radio"]').on("change", function (event) {
    console.log($(this).prop('tagName'));// INPUT
    console.log($(this).attr('type'));// checkbox or radio
});

回答by Shadow

you can use

您可以使用

function test(e)
{
   var eve = e || window.event;
   var ele = eve.target || eve.srcElement;

   switch(ele.getAttribute('type'))
   {
     case "radio" : //do whatever

     case "checkbox" : //do
   }

}

回答by Pranav Gupta

you can use event.target.getAttribute('type')instead

您可以使用event.target.getAttribute('type')替代

回答by Pranav Gupta

For the node type with jQuery you can use:

对于带有 jQ​​uery 的节点类型,您可以使用:

  • $(event.target).attr('type')
  • event.target .type
  • $(event.target) .attr('type')
  • 事件.目标.类型
$("SELECTOR").click(function (event) {
var idEventTarget = $(event.target).attr('id');
console.log($(event.target).attr('type'));
console.log(event.target.type);
});
$("SELECTOR").click(function (event) {
var idEventTarget = $(event.target).attr('id');
console.log($(event.target).attr('type'));
console.log(event.target.type);
});