小记:jQuery里parent和parents的差别

今天写代码的时候碰到了一个问题,大体问题是这样的

HTML代码:


![]({{imageHost}}{{productMainImage}}) {{productName}} ¥{{productPrice}} - + ¥{{productTotalPrice}} 删除

JS代码:

 var $this = $(this), productId = $this.parents('.cart-table').data('product-id');

点击一个多选框,并读取其类名为cart-table的祖先元素的自定义属性 data-product-id,然而最开始犯错的地方就是我用了parent 而没有用parents。代码执行之后productId的值变成了undefined


然后我就做了几次尝试,如下

HTML:

JS:

$(document).ready(function () {
        var name = $('li').parent('.div1').data('name');
        document.writeln(name);
    });

期待的结果是myName,然而

image.png

喜闻乐见,我就去问了度娘和谷歌,然后改了一下,

JS:

$(document).ready(function () {
        var name = $('li').parents('.div1').data('name');
        document.writeln(name);
    });

then,成功了。

小记:jQuery里parent和parents的差别_第1张图片
image.png

大致的结果让我明白了parent只能网上推一级,也就是找到父元素,而不会再继续往上找祖先元素,而parents更像是将祖先元素收集起来,然后获取我们加了给定条件的那一个祖先元素。

以下是做了几次小尝试的对比图,放上来看一下
HTML:

JS:

$(document).ready(function () {
        var name    = $('li').parents('.div1').data('name'),
            color   = $('li').parents('.ul1').data('color'),
            age     = $('li').parent('.ul1').data('age'),
            height  = $('li').parent('.div1').data('height');
        document.writeln(name + "\n" + color + "\n" + age+ "\n" + height);
    });

结果:

image.png

That's all for today...

你可能感兴趣的:(小记:jQuery里parent和parents的差别)