2013-08-30 43 views
0

我有以下的播放列表行,这些行已在播放列表中存在检查多给出链接选定的链接匹配

<div class="total-row"> 
    <div class="total-title" src="music/04_LCR_Mae_Terra.mp3">04_LCR_Mae_Terra</div> 
</div> 
<div class="total-row"> 
    <div class="total-title" src="music/06LCR_Homem_Mal.mp3">06LCR_Homem_Mal</div> 
</div> 
<div class="total-row"> 
    <div class="total-title" src="music/06LCR_Homem_Mal.mp3">06LCR_Homem_Mal</div> 
</div> 

而且我有链接添加的歌曲在播放列表

<div id="playlinks"> 
    <li mp3="music/04_LCR_Mae_Terra.mp3" class="add_link"></li> 
    <li mp3="music/05_LCR_Jack_Matador.mp3" class="add_link"></li> 
</div> 

所以我会匹配选定的(点击)链接的MP3链接与播放列表中的已存在链接(我将匹配所有行),如果已经存在,那么它不会添加,如果不存在,然后添加选定的一个。我使用下面的jQuery代码

if i use the below code 

$(document).on("click", ".add_link", function(){ 

    var mp3 = $(this).attr("mp3"); 
    var foundInPlaylist = 
     $(".total-row .total-title[src$='"+ ('/'+mp3) +"']").length; 
    if(foundInPlaylist){ 
     alert("found"); 
    } else{ 
     alert("not found"); 
    } 
}); 

这不工作,即使我只是写警报(foundInPlaylist);它警告“0”;

​​

它也不会为我

感谢

+0

嗨,他们似乎为我工作,直接复制回来上面的代码(MacSafari 5.1.9 + MacFirefox 23.0.1):http://jsfiddle.net/KRnWR/3/ http://jsfiddle.net/KRnWR/4/ – biziclop

+0

叶@biziclop现在为我工作,我更改您的声明 ('/'+ mp3) 至 (mp3) 并且此工作,谢谢 –

+0

不客气:) – biziclop

回答

0

工作,也许你可以尝试使用jQuery选择$("[attribute$='value']") “属性结尾”:

http://api.jquery.com/attribute-ends-with-selector/

快速例子小提琴:http://jsfiddle.net/KRnWR/2/

// http://api.jquery.com/on/ 
$(document).on("click", ".add_link", function(){ 

    var mp3 = $(this).attr("mp3"); 

    // http://api.jquery.com/attribute-ends-with-selector/ 
    var foundInPlaylist = 
     $(".total-row .total-title[src$='"+ ('/'+mp3) +"']").length; 

    // for (brain)killing programmers :) 
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else 
    if(foundInPlaylist){ 
     alert(mp3 + ' found in playlist.'); 
    }else{ 
     alert(mp3 + ' not found in playlist.'); 
    } 
}); 

我在前面加上'/'的MP3文件名之前,以防止错误匹配这样的:

  mp3="lala.mp3"> 
src="music/lalalala.mp3"> 
+0

谢谢,但我希望对点击事件进行操作,并检查所有链接并仅提醒一次,意味着当我点击一个给定的链接,然后检查所有的行,如果该src存在于其中一个然后警告只有一次,这个src已经存在 –

+0

嗨,我更新我的答案是更clicky,我改变'click()'为'on()'是因为。 :)顺便说一句,我的解决方案可能会失败,文件名有趣的字符,例如引号。 – biziclop

+0

谢谢biziclop可以请简化警报声明意味着你写在(if,else)语句,因为我需要写一个大代码如果不存在播放列表 –

0

请试试这个代码:

$(".add_link").click(function() { 
var newMp3 = $(this).attr("mp3"); 
var exists = false; 
$(".total-row").each(function(){ 
    var oldmp3 = $(this).children(".total-title").attr("src"); 
    if(oldmp3.indexOf(newMp3) > -1) 
    { 
     exists = true 
    } 


}); 
if(exists) 
{ 
    alert("song already exists"); 
} 
else { 
     alert("song does not exist"); 
    } 
}); 

这里工作示例:

http://jsfiddle.net/YW46k/

+0

嗨,@Adam plz检查编辑的问题 –

+0

我犯了一个错误。更改行“oldmp3.indexOf(newMp3)> -1”(0变成-1),它将工作:http://jsfiddle.net/YW46k/1/ –