检查所选链接在多个给定链接中是否匹配

Check if the selected link match in multiple given links

本文关键字:链接 是否 检查      更新时间:2023-09-26

我有以下播放列表行,这些行已经存在于播放列表中

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

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

它也不适用于我

感谢

也许您可以尝试使用jQuery"attribute ends with"选择器$("[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">

请尝试此代码:

$(".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/