繁体   English   中英

如何在jQuery中使用多个选择器

[英]How to use multiple selectors with jQuery

这是我正在使用的代码(工作正常,直到客户端上传新图像-然后必须对其进行修改才能再次工作:

 $( document ).ready(function() { var firstProduct = $('.post-416 .woocommerce-loop-product__title').html(); jQuery('.post-416 h2.woocommerce-loop-product__title').remove(); var firstPrice = $('.post-416 .price').html(); jQuery('.post-416 .price').remove(); console.log(firstProduct + firstPrice); var secondProduct = $('.post-186 .woocommerce-loop-product__title').html(); jQuery('.post-186 h2.woocommerce-loop-product__title').remove(); var secondPrice = $('.post-186 .price').html(); $('.post-186 .price').remove(); var thirdProduct = $('.post-413 .woocommerce-loop-product__title').html(); $('.post-413 h2.woocommerce-loop-product__title').remove(); var thirdPrice = $('.post-413 .price').html(); $('.post-413 .price').remove(); var fourthProduct = $('.post-218 .woocommerce-loop-product__title').html(); $('.post-218 h2.woocommerce-loop-product__title').remove(); var fourthPrice = $('.post-218 .price').html(); $('.post-218 .price').remove(); var linebreak = ("<br>") $( ".post-416 .et_overlay" ).append(firstProduct + linebreak + firstPrice); $( ".post-186 .et_overlay" ).append(secondProduct + linebreak + secondPrice); $( ".post-413 .et_overlay" ).append(thirdProduct + linebreak + thirdPrice); $( ".post-218 .et_overlay" ).append(fourthProduct + linebreak + fourthPrice); }); 

我正在尝试用这样的东西代替它

 jQuery( document ).ready(function() { var postClasses = jQuery("li[class*='post-").toArray(); jQuery( postClasses[0] ).each(function( index ) { console.log( index + ": " + jQuery( this ).text() ); }); jQuery( ".et_overlay:first" ).appendTo(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

问题出在第一部分,我能够抓住也共享类.woocommerce-loop-product__title所有post-*元素,而在第二部分中尝试这样做时,我将抓住post- *,当我只想获取post-*.woocommerce-loop-product__title

我如何使用多个jQuery选择器( 尤其是Attributes Contains Selector )来完成此任务? 如果这不是正确的解决方案,那我应该如何处理呢?

假设您的意思是您不想每次有人上传时都添加一行,请使用通配符选择器:

jQuery('[class^="post-"] .woocommerce-loop-product__title').html()

它将选择所有父元素的类名称都以'post-'开头的元素.woocommerce-loop-product__title 如果'post-'不是这些元素中的第一个类名称,请改用此名称:

jQuery('[class*="post-"] .woocommerce-loop-product__title').html()

使用这样的东西

$(document).ready(function() {
  /*if the post-* elements have the product class use it*/
  var posts = $('.product'), // or $('[class*="post-"])
    linebreak = '<br>';


  posts.each(function() {
    var self = $(this),
        title = self.find('.woocommerce-loop-product__title'),
        price = self.find('.price'),
        overlay = self.find('.et_overlay');

    overlay.append(title.html() + linebreak + price.html());

    title.remove();
    price.remove();
  });

});

暂无
暂无

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

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