单击颜色时,会创建一个对象.
$(document).off("click", ".color").on("click", ".color", function (event) {
var result = {};
$.each($('.color input').serializeArray(), function() {
result[this.name] = this.value;
});
console.log(result);
});
.color{height:100px;width:200px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color" style="background-color:pink">
<input type="hidden" name="name" value="fred">
<input type="hidden" name="id" value="23">
</div>
<div class="color" style="background-color:blue">
<input type="hidden" name="name" value="laura">
<input type="hidden" name="id" value="14">
</div>
但我希望实现点击颜色的对象被创建.
$(document).off("click", ".color").on("click", ".color", function (event) {
var result = {};
var this = $(this);
$.each($(this 'input').serializeArray(), function() {
result[this.name] = this.value;
});
console.log(result);
});
.color{height:100px;width:200px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color" style="background-color:pink">
<input type="hidden" name="name" value="fred">
<input type="hidden" name="id" value="23">
</div>
<div class="color" style="background-color:blue">
<input type="hidden" name="name" value="laura">
<input type="hidden" name="id" value="14">
</div>
解决方法:
如下所示: –
$.each($(this).find('input').serializeArray(), function() {
工作片段: –
$(document).off("click", ".color").on("click", ".color", function (event) {
var result = {};
$.each($(this).find('input').serializeArray(), function() {
result[this.name] = this.value;
});
console.log(result);
});
.color{
height:100px;
width:200px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color" style="background-color:pink">
<input type="hidden" name="name" value="fred">
<input type="hidden" name="id" value="23">
</div>
<div class="color" style="background-color:blue">
<input type="hidden" name="name" value="laura">
<input type="hidden" name="id" value="14">
</div>
注意: – 我无法在您的代码中看到.off()方法的重要性,所以您可以尝试: –
$(document).on("click", ".color", function (event) {
确保此更改不会影响其他代码的其余部分