考虑简单的多选框
<select name="waste" id="waste" multiple>
<option value="5">garbage</option>
<option value="6">food</option>
<option value="8">Tin</option>
<option value="9">Can</option>
</select>
所有这一切都是火灾变化事件
$('#waste').change(function(){
//Inside here how will I know that this event was fired when user removed some values from selection
// or did he added more values in selection
});
答案 0 :(得分:1)
尝试此示例:http://jsfiddle.net/7rf9J/
(function() {
var s = $('#waste'),
var i = s.val().length;
s.change(function(){
var l = $(this).val().length;
if (l === i) {
console.log('you\'ve not changed selected value/s');
}
else {
if (l > i) {
console.log('you inserted value/s');
}
else {
console.log('you removed value/s');
}
}
i = l;
});
}());
我已将函数包含在一个立即自执行函数中,其中我声明了一个包含所选项数的变量。每次添加o删除项目时,我都会保存当前值的长度(最初设置为0),因此您知道是否添加,删除或更改了选择。
答案 1 :(得分:0)
试试这个:
$('#waste').change(function(){
var selected=$(this).val();
// selected now contains an array of the selected values
});
答案 2 :(得分:0)
我写了一个可以完全满足你需要的例子。 示例如下:http://jsfiddle.net/hesher/3M36e/5/
代码:
var prevarray = [];
$("select").change(function(event) {
var
thisarray = $(event.currentTarget).children(":selected").map(function(index, item) {
return $(item).text()
});
for (i = 0; i < thisarray.length; i++) {
var anoption = thisarray[i];
if ($.inArray(anoption, prevarray) === -1) {
console.log("added " + anoption);
}
}
for (i = 0; i < prevarray.length; i++) {
var anoption = prevarray[i];;
if ($.inArray(anoption, thisarray) === -1) {
console.log("removed " + anoption);
}
}
prevarray = thisarray;
});
答案 3 :(得分:0)
试试这个:
<select name="waste" id="waste" multiple>
<option value="5">garbage</option>
<option value="6">food</option>
<option value="8">Tin</option>
<option value="9">Can</option>
</select>
<p></p>
和js是:
function displayVals() {
var wasteValues = $("#waste").val() || [];
$("p").html("<b>Values:</b> " + multipleValues.join(", "));
}
$("#waste").change(displayVals);
displayVals();
或检查一下:http://api.jquery.com/val/希望这有助于您:]