在处理事件时,如何定位具有特定类的元素

How do you target an element with a specific class when handling an event?

本文关键字:元素 定位 处理事件 何定位      更新时间:2023-09-26

JQuery 新手,仍在学习...

下面的脚本在单击图像时交换div 的类。如何隔离图像,以便只有类为 .thumbnail 的图像触发脚本?

< script >
  $(document).ready(function(){
    $("img").click(function(e) {
      var newclass = $(this).attr("class");
      var oldclass = $("#fullsize").attr('class');
      $("#fullsize").removeClass(oldclass).addClass(newclass);
    })
  }); 
< /script>

>$('img')将选择文档中的所有IMG。

$('img.thumbnail')将选择文档中具有thumbnail类的所有 img。

您可以通过替换类属性来组合removeClass addClass操作。

$('img.thumbnail').click(function(e) {
    var newclass = $(this).attr('id');
    var oldclass = $('#fullsize').attr('class');
    $('#fullsize').attr('class',newClass); // Note: No need to removeClass and then addClass. Simply Replace the value of class attribute.
});
$("img.thumbnail ").click(function(e) { // add the class along with the img selector
  var newclass = $(this).attr("id");
  var oldclass = $("#fullsize").attr('class');
  $("#fullsize").removeClass(oldclass).addClass(newclass);
})

此链接可以帮助您了解jQuery中的不同选择器

你可以这样做

<script>
 $(document).ready(function() {       
   $("img.thumbnail").click(function(e) {           
     var newclass = $(this).attr("id");               
     var oldclass = $("#fullsize").attr('class');  
     $("#fullsize").removeClass(oldclass).addClass(newclass);  
   });                  
});
</script>