我正在尝试删除点击的ID以删除输入值。例如,我有这个输入<input type='hidden' id='uploadvalues' value="8,9"/>
您可以看到值8,9
,按钮是<div class="delete" id="9"></div>
。
当我单击id="9"
时,应删除输入值9。点击id="9"
==&gt;后<input type='hidden' id='uploadvalues' value="8"/>
我怎么能这样做,任何人都可以教我?
来自CodeCanyon的<div class="container">
<div class="area">
<div class="image"><img src="https://s-media-cache-ak0.pinimg.com/736x/05/2f/1b/052f1b3a2361eb4f3c1385c1fd4f75ed.jpg"></div>
<div class="delete" id="8"></div>
</div>
<div class="area">
<div class="image"><img src="http://www.wallpapermade.com/images/wallpapers/originals/tip-and-oh-laugh-together-home-2015-movie-wallpaper-4612.jpg"></div>
<div class="delete" id="9"></div>
</div>
<input type='hidden' id='uploadvalues' value="8,9"/>
</div>
JS
$(document).ready(function(){
$("body").on("click", ".delete", function(){
// Remove clicked id from the input value
});
});
答案 0 :(得分:2)
制作
$(document).ready(function(){
$("body").on("click", ".delete", function(){
var val = $(this).attr("id");
var values = $( "#uploadvalues" ).val().split(",");
var valIndex = values.indexOf(val);
if (valIndex > -1)
{
values.splice(valIndex,1);
}
$( "#uploadvalues" ).val( values.join(",") )
});
});
答案 1 :(得分:2)
您想要的方法之一是
$("body").on("click", ".delete", function(){
var id = this.id, //extract the id from the clicked element
values = $('#uploadvalues').val().split(','), // get the existing values in the #uploadvalues element
remaining = values.filter(function(val){ // filter out the ones equal to the id of the clicked element
return val !== id;
});
$('#uploadvalues').val(remaining.join()); // update the changed values
});
答案 2 :(得分:1)
尝试在此背景下使用regular expression
,
$(document).ready(function() {
$("body").on("click", ".delete", function(){
var id = this.id;
$("#uploadvalues").val(function(val){
return val.replace(new RegExp(id + "\,|\,"+ id +"$"),"")
});
});
});
答案 3 :(得分:1)
当你点击删除按钮时,在回调函数中获取id:
var valueToRemove = this.id;
// now you need to look to see if that value is inside the hidden input
var valueToRemove = this.id;
console.log(valueToRemove);
var values = $("#uploadvalues").val();
if(values.indexOf(valueToRemove) >= 0){
$("#uploadvalues").val(values.replace(valueToRemove,""));
}
也是缓存dom的最佳实践,因此您不必经常查询它。
这是你想要的吗?并且此方法不会删除值中的逗号。