2012-02-16 38 views
2

我有名字的數組,我需要看看他們在一個DIV匹配的名字:匹配陣列與DIV文本

var topicName = []; 
$.each(top3, function(i, item) { 
    if (item.featured === false) { 
     topicName.push(item.username); 
    }  
}); 

$("DIV.grid_6 DIV.name").each(function(i, item){ 
     if (topicName === item){ 
     alert("do somethign"); 
     } 
    } 

我有一堆DIV.name類的,如果名稱匹配topicName數組,我需要做一些事情;

+1

你的第二個'if'語句很痛苦。修復你的'()'和'{}'請 – Ktash 2012-02-16 19:28:41

+0

你能發佈html嗎? – elclanrs 2012-02-16 19:33:12

+0

什麼是'if(topicName === item){}'?如果'topciName'是一個數組,你不能只比較那些值。 – elclanrs 2012-02-16 19:35:29

回答

0

HTML:

<div class="name">jen</div> 
<div class="name">bob</div> 
<div class="name">sally</div> 

的jQuery:

var topicName = ["jen","bob","michelle"]; 


$("div.name").each(function(){ 

    var nameFound = $.inArray($(this).text(), topicName); 
    if (nameFound === -1){ 
     alert($(this).text() + " not found in array"); 
    } else { 
     alert($(this).text() + " found in array"); 
    } 

}); 

http://jsfiddle.net/xqGKr/

1
$("DIV.grid_6 DIV.name").each(function(i, item){ 
    if ($.inArray(item, topicName) !== -1){ 
     alert("do somethign"); 
    } 
} 
0

而不是

if (topicName === item) 

做到這一點,如果匹配的文本是div的內容:

if ($.inArray($(item).text(), topicName) != -1) 

,或者如果它在一個屬性(如<div name="foo">) :

if ($.inArray($(item).attr('name'), topicName) != -1) 
0

你可以使用某種類似這樣取巧的方法;

$(document).ready(function(){ 
    var a = ['foo', 'bar', 'c']; 
    // 
    // $('.' + a.join(', .')) => $('.foo, .bar, .c') 
    // 
    $('.' + a.join(', .')).mouseover(function() { 
     console.log($(this).attr('class')); 
    }); 
}); 

你可以簡單地選擇它們,做你想做的事。如果名稱不存在,則不會有綁定。這意味着沒有任何問題。