Javascript jQuery.on with.get方法
当用户单击元素时,我试图获取在Javascript jQuery.on with.get方法,javascript,jquery,html,Javascript,Jquery,Html,当用户单击元素时,我试图获取在li中单击的元素的标记名。li元素被动态添加到HTML代码中。要做到这一点,我使用下面的代码,但它似乎不工作 $('li *','div#contentWrapper').on('click','#interfaceContainer #left #sortableTestComponents li',function(e){ e.stopPropagation(); var domEl = $(this).get(0);
li
中单击的元素的标记名。li
元素被动态添加到HTML代码中。要做到这一点,我使用下面的代码,但它似乎不工作
$('li *','div#contentWrapper').on('click','#interfaceContainer #left #sortableTestComponents li',function(e){
e.stopPropagation();
var domEl = $(this).get(0);
alert(domEl.tagName);
if(!$(event.target).hasClass("deleteTestComp")){
var type = $(this).find('div.headerName').html();
var information = $(this).find('input[type=hidden]').val();
if(type == "CliSessionType"){
parseCliComponent(information);
}
else if(type == "DBSessionType"){
parseDbComponent(information);
}
else{
parseScreenComponent(information);
}
}
});
为什么我的代码不起作用?当用户单击元素时,不会发生任何事情
jsidle-您正试图在选择器中使用一个不需要的上下文。将
$('li*'、'div#contentWrapper')
更改为$('div#contentWrapper')
,将$(event.target)
更改为$(e.target)
。一把小提琴正在工作
由于您对
#interfaceContainer
下的li
元素中的单击事件感兴趣,因此事件注册必须是$(“#interfaceContainer”)。on('click','li',函数(e){…})代码>
然后,要获取标记名,您需要使用事件的实际来源,这在e.target
中可用,因此您需要使用$(e.target).get(0)
来获取单击的dom元素
$('#interfaceContainer').on('click','li',function(e){
e.stopPropagation();
var domEl = $(e.target).get(0);
alert(domEl.tagName);
if(!$(event.target).hasClass("deleteTestComp")){
var type = $(this).find('div.headerName').html();
var information = $(this).find('input[type=hidden]').val();
if(type == "CliSessionType"){
parseCliComponent(information);
}
else if(type == "DBSessionType"){
parseDbComponent(information);
}
else{
parseScreenComponent(information);
}
}
});
演示:您能给我们展示一个工作示例吗?或者展示一些您正在使用的代表性标记吗?创建了一个提琴-您的代码似乎表明您在div#contentWrapper和单击的li之间至少有7个级别。是这样吗?发布html会有帮助。是的,就是这样,html在JSFIDLE中,你想要所有的html吗,因为有很多。
$('#interfaceContainer').on('click','li',function(e){
e.stopPropagation();
var domEl = $(e.target).get(0);
alert(domEl.tagName);
if(!$(event.target).hasClass("deleteTestComp")){
var type = $(this).find('div.headerName').html();
var information = $(this).find('input[type=hidden]').val();
if(type == "CliSessionType"){
parseCliComponent(information);
}
else if(type == "DBSessionType"){
parseDbComponent(information);
}
else{
parseScreenComponent(information);
}
}
});