比较每个循环jquery中运行的两个值

时间:2014-01-27 22:38:33

标签: javascript jquery

我将冒号分隔值存储在html元素的数据属性中

<a class='te' data-tes='test123;123test;234test'>test</a>
<a class='te' data-tes='t3;1st;123test'>test1</a>

我想要一个返回公共值的函数。在上面的示例中,只有123test匹配。到目前为止,这是我尝试过的

$('.te').each(function(){
    if($(this).data('tes')!= undefined){
        # Here how can i perform the comparision.
    }
})

2 个答案:

答案 0 :(得分:0)

您可以首先创建一个存储每个数据属性的数组,在;

分割
var arr = [];
$('.te').each(function() {
    arr.push($(this).data('tes').split(';'));
});

这将在您的示例中创建一个这样的数组:

[
    ["test123", "123test", "234test"],
    ["t3", "1st", "123test"]
]

之后,你必须在每个值中运行一个循环来比较它们:

for (var i=0;i<arr[0].length;i++) {
    if (arr[0][i] == arr[1][i]) {
        //This will only run when the first element's data-tes attribute's value is equal to the second element's. In this case, that'll be for the third value - at i==2.
    }
}

答案 1 :(得分:0)

怎么样?
var results = {};

$( ".te" ).each( function( ) {

    var parts = $(this).data( 'tes' ).split( ";" );

    // in case the same string is present twice in
    // same element and nowhere else
    var added = {};

    for( var i = 0; i < parts.length; i++ ) {

        // this string is not in results yet
        if( results[ parts[i] ] == undefined ) {
            results[ parts[i] ] = 1;
            added[ parts[i] ] = 1;
        } // it is in results & if not already present in this string then add
        else if( !added[ parts[i] ] ) {
            results[ parts[i] ]++;
            // record that string is found in this element
            added[ parts[i] ] = 1;
        }
    }

});

对于你的例子,这会产生

{"test123":1,"123test":2,"234test":1,"t3":1,"1st":1}

值为2或更多的项目是至少出现在2个元素中的项目。如果您的要求是它存在于所有元素中,则该值必须与元素数量匹配。

小提琴here