当我点击颜色时,会创建一个对象。
$(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>
&#13;
但我希望实现点击颜色的对象的创建。
$(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);
});
&#13;
.color{height:100px;width:200px}
&#13;
<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>
&#13;
答案 0 :(得分:5)
如下所示: -
$.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);
});
&#13;
.color{
height:100px;
width:200px
}
&#13;
<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>
&#13;
注意: - 我无法在您的代码中看到.off()
方法的重要性,因此您可以尝试: -
$(document).on("click", ".color", function (event) {
确保此更改不会影响其他代码的其余部分
答案 1 :(得分:2)
你可以试试这个:
$(".color").click(function (event) {
var result = {};
$.each($(this).find('input').serializeArray(), function() {
result[this.name] = this.value;
});
console.log(result);
});
&#13;
.color{height:100px;width:200px}
&#13;
<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>
&#13;