我有以下播放列表行,这些行已存在于播放列表中
<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");
}
});
它也不适合我
由于
答案 0 :(得分: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">
答案 1 :(得分: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");
}
});
这是工作示例: