我很努力地理解为什么jQuery函数“on change”只能为每行工作一次。代码我已经完美地适用于对每行进行多处更改,但是当我更改“相反值”时,代码将失败。JavaScript更改函数只触发一次
我认为这是因为第一个选择器$(".line").children()
已被设置,然后不是'unset'为每个。我也浏览过以前对类似问题的回答,但没有取得任何成功。
有没有办法改变它?我尝试使用.unbind()
进行未设置,但仅仅是在第一次后停止执行代码。
$(".line").children().on("change", function(event) {
console.log($(this).children());
if ($(this).children().attr("class").includes("picker")) {
$(this).parent().find(".hex").attr("value", $(this).find(".picker").val());
} else {
$(this).parent().find(".picker").attr("value", $(this).find(".hex").val());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="col-md-12 form">
<h3>Palette name : <span id="palette_name"></span></h3>
<div class="line">
<div class="form-group col-md-5">
<input type="color" class="form-control picker" value="#ffffff" id="picker1">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control hex" value="#ffffff" id="hex1">
</div>
</div>
<div class="line">
<div class="form-group col-md-5">
<input type="color" class="form-control picker" value="#ffffff" id="picker2">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control hex" value="#ffffff" id="hex2">
</div>
</div>
<div class="line">
<div class="form-group col-md-5">
<input type="color" class="form-control picker" value="#ffffff" id="picker3">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control hex" value="#ffffff" id="hex3">
</div>
</div>
<div class="line">
<div class="form-group col-md-5">
<input type="color" class="form-control picker" value="#ffffff" id="picker4">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control hex" value="#ffffff" id="hex4">
</div>
</div>
</div>
<div class="col-md-10">
<a class="btn btn-info btn-lg">Update</a>
<a class="btn btn-danger btn-lg pull-right cancel" href="index.html">Cancel</a>
</div>
</form>
为什么不使用'hasClass'? – Li357
我不确定如果我确切地得到了您的问题描述,但[是在这里转载的同样的错误](https://jsfiddle.net/kfb7yk66/)?因为这个事件监听器似乎在我预期的时候正好触发。 –
为什么不使用每个? $(“.form-control”).each(function(index){ \t \t }); – kanzari