gpt4 book ai didi

javascript - 如何在jQuery中继续执行点击事件?

转载 作者:行者123 更新时间:2023-11-28 16:00:28 25 4
gpt4 key购买 nike

第一次,在页面加载时,我单击豪华版,并且单击事件成功。但是,当我点击另一个选项并再次点击豪华选项后,点击事件不成功。

如何让它发挥作用?

这是我的代码:

<!doctype html>
<html>
<head>
<title>A Basic Form</title>
<script type="text/javascript" src="scripts/jquery-1.10.1.min.js">
</script>
</head>
<body>
<h1>
A Basic Form</h1>
<hr>
<form action="#">
<fieldset>
<legend>Car Trim and Package Information</legend>
<div class="form-field">
<div>
Package:
</div>
<input id="plain" type="radio" name="trim" value="plain">
<label for="plain">
Plain</label>
<input id="deluxe" type="radio" name="trim" value="deluxe">
<label for="deluxe">
Deluxe</label>
<input id="custom" type="radio" name="trim" value="custom">
<label for="custom">
Custom</label>
</div>
<div class="form-field">
<div>
Extra Options:</div>
<input type="checkbox" id="foglights" name="option" value="foglights">
<label for="foglights">
Fog Lights</label>
<input type="checkbox" id="leather" name="option" value="leather">
<label for="leather">
Leather</label>
<input type="checkbox" id="dvd" name="option" value="dvd">
<label for="dvd">
DVD</label>
</div>
<div class="form-field">
<input id="submit" type="submit" name="submit" value="Send Form">
</div>
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("input[name='trim']").click(function (event) {
if ($(this).val() == "deluxe") {
$("input[name='option']").attr("checked", true);
} else if ($(this).val() == "plain") {
$("input[name='option']").attr("checked", false);
}
});
$("input[name='option']").click(function (event) {
$("#custom").attr("checked", "checked");
});
});
</script>
</body>
</html>

最佳答案

使用.prop()而不是.attr() .

attr() 不起作用的原因是,

属性和特性之间的区别在特定情况下可能很重要。在 jQuery 1.6 之前,.attr() 方法有时在检索某些属性时会考虑属性值,这可能会导致行为不一致。

所以,从 jQuery 1.6 开始,.prop() 方法提供了一种显式检索属性值的方法,而 .attr() > 检索属性。

你的最终代码将是,

$("input[name='trim']").click(function (event) {
if ($(this).val() == "deluxe") {
$("input[name='option']").prop('checked', true);
} else if ($(this).val() == "plain") {
$("input[name='option']").prop('checked', false);
}
});
$("input[name='option']").click(function (event) {
$("#custom").prop('checked', true);
});

关于javascript - 如何在jQuery中继续执行点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17184241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com