javascript 将数据添加到每个函数中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14991510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:05:41  来源:igfitidea点击:

add data to element in each function

javascriptjqueryhtml

提问by Chris G-Jones

I made an each function that counts the images inside a div and I am trying to set the number of images counted inside the div as a data attribute for the div but it is not working.

我创建了一个计算 div 内图像的 each 函数,我试图将 div 内计数的图像数量设置为 div 的数据属性,但它不起作用。

Have I gone about this the wrong way because it does not seem to be working?

我是否以错误的方式解决了这个问题,因为它似乎不起作用?

Here is the site http://www.touchmarketing.co.nz/test/

这是网站http://www.touchmarketing.co.nz/test/

    var mostImages = 0;

    numSliders = $wowSlides.length,
    lastVindex = numSliders-1;

    $wowSlides.each(function(){

        var $this = $(this),
        $images = $this.find('img'),
        numImages = $images.length;

        $images.css({width:$slideWidth, 'float':'left', 'position':'relative'}).wrapAll('<div class="slider" />');
        $slider = $this.find(".slider");
        $slider.width($slideWidth*numImages).css({'float':'left'});                     

        $this.data('count', numImages); // add data-count="insert number here" to this .wowSlides div

        console.log(numImages); 

        if(numImages > mostImages){

            mostImages = numImages;

        }                   

    });

回答by the system

This sets data to jQuery's proprietary data cache:

这将数据设置到 jQuery 的专有数据缓存:

$this.data('count', numImages);

It doesn't set to a data-attribute of the element. Generally there shouldn't be a need to set a data-attribute on the client, since its purpose is to transfer data from server to client.

它没有设置为data-元素的属性。通常不需要data-在客户端上设置属性,因为它的目的是将数据从服务器传输到客户端。

Nevertheless, if you want to set it, use

不过,如果您想设置它,请使用

$this.attr('data-count', numImages)

or

或者

this.setAttribute('data-count', numImages)


Personally, if I wanted to associate a small amount of data with an element, I'd just store it as a property directly on the element itself.

就个人而言,如果我想将少量数据与元素相关联,我只需将其作为属性直接存储在元素本身上。

this.count = numImages;

For primitive data, it's harmless. For larger objects or other DOM elements, I'd be more hesitant.

对于原始数据,它是无害的。对于更大的对象或其他 DOM 元素,我会更犹豫。