繁体   English   中英

用 jQuery 检查哪个元素被点击

[英]Check which element has been clicked with jQuery

我正在尝试使用“if”语句来确定单击了哪个元素。

基本上我试图编码一些东西:

if (the element clicked is '#news_gallery li .over') {
    var article = $('#news-article .news-article');
} else if (the element clicked is '#work_gallery li .over') {
    var article = $('#work-article .work-article');
} else if (the element clicked is '#search-item li') {
    var article = $('#search-item .search-article');
};

什么是正确的 jQuery 语法? 提前谢谢了。

使用这个,我想我能明白你的想法。

现场演示: http : //jsfiddle.net/oscarj24/h722g/1/

$('body').click(function(e) {

    var target = $(e.target), article;

    if (target.is('#news_gallery li .over')) {
       article = $('#news-article .news-article');
    } else if (target.is('#work_gallery li .over')) {
       article = $('#work-article .work-article');
    } else if (target.is('#search-item li')) {
       article = $('#search-item .search-article');
    }

    if (article) {
       // Do Something
    }
});​

所以你这样做有点倒退。 通常你会做这样的事情:

​<div class='article'>
  Article 1
</div>
<div class='article'>
  Article 2
</div>
<div class='article'>
  Article 3
</div>​

然后在你的 jQuery 中:

$('.article').click(function(){
    article = $(this).text(); //$(this) is what you clicked!
    });​

当我看到诸如#search-item .search-article#search-item .search-article#search-item .search-article我感觉您过度指定了 CSS,这使得编写简洁的 jQuery 变得非常困难。 如果可能的话,应该避免这种情况。

vpiTriumph 的回答很好地列出了细节。
当您要访问的数据集具有唯一元素 ID 时,这是一个方便的小变化:

$('.news-article').click(function(event){    
    var id = event.target.id;
    console.log('id = ' + id); 
});

另一种选择是利用e.targettagName属性。 它并不完全适用于这里,但假设我有一类应用于DIVA标记的东西,我想查看是否单击了该类,并确定它是DIV还是A被点击。 我可以做这样的事情:

$('.example-class').click(function(e){
  if ((e.target.tagName.toLowerCase()) == 'a') {
    console.log('You clicked an A element.');
  } else { // DIV, we assume in this example
    console.log('You clicked a DIV element.');
  }
});

jQuery 的基础是能够通过选择器在 DOM 中查找项目,然后检查这些选择器的属性。 在此处阅读选择器:

http://api.jquery.com/category/selectors/

但是,为基于单击的内容应发生的不同功能的单击事件创建事件处理程序会更有意义。

希望这对你有用。

$(document).click(function(e){
    if ($('#news_gallery').on('clicked')) {
        var article = $('#news-article .news-article');
    }  
});
$("#news_gallery li .over").click(function() {
    article = $("#news-article .news-article");
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM