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");
     }
});

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

if i use the second solution

$(".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) > 0 )
    {
        exists = true
    }
});
if(exists)
{
    alert("song already exists");
}
else {
        alert("song does not exist");
    }
});

它也不适合我

谢谢

4

2 回答 2

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">
于 2013-08-30T07:50:58.650 回答
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/

于 2013-08-30T08:51:07.857 回答