这是我在 Stack Overflow 上的第一个问题。我通常通过搜索找到所有答案,但在编写以下代码后我完全失去了动力。
是否有更有效的方法或简写来编写以下代码?
目前它完全符合我的要求。当您单击单选按钮时,会在该单选按钮旁边加载一个 div。如果您切换单选按钮,它会删除 div 并在该单选按钮旁边创建一个新的。
我对实际编写自己的 JavaScript/jQuery 还很陌生。我知道 CASE,但我不完全确定这是否适合它。
如有任何建议,我们将不胜感激。
jQuery(document).ready(function($) {
var checkedItem = true;
$('form input').click(function(){
if (checkedItem == true){
$(this).siblings('div.next').remove('.checked');
$(this).after('<div class="next">NEXT</div>');
$(this).siblings('div.next').addClass('checked');
checkedItem = false;
}
else {
$(this).siblings('div.next').remove('.checked');
$(this).after('<div class="next">NEXT</div>');
$(this).siblings('div.next').addClass('checked');
checkedItem = true;
}
});
});
<form id="input-form">
<input class="PAD" type="radio" name="Seasons" value="Spring-Fall" /> Spring-Fall<br />
<input class="PAD" type="radio" name="Seasons" value="Winter" /> Winter
</form>
最佳答案
如果您使用的是 jQuery 1.7+,您可以:
HTML
<form id="input-form">
<input class="PAD" type="radio" name="Seasons" value="Spring-Fall" />
Spring-Fall<br />
<input class="PAD" type="radio" name="Seasons" value="Winter" /> Winter
</form>
jQuery
$(function() {
$("input[type=radio]").click(function() {
if ($(this).is(":checked")) {
$(this).siblings('.next').remove('.checked');
$(this).after('<div class="next">NEXT</div>');
$(this).siblings('.next').addClass('checked');
}
else { // fyi, this, or your var is kinda useless redundancy, but just for purpose of show, here ya go
$(this).siblings('.next').remove('.checked');
$(this).after('<div class="next">NEXT</div>');
$(this).siblings('.next').addClass('checked');
};
});
});
尽管您可以通过以下方式轻松简化整个事情:
$(function() {
$("input[type=radio]").click(function() {
$(this).siblings('.next').remove();
$(this).after($("<div />").addClass("next checked").text("NEXT"));
});
});
关于javascript - 以下代码的速记或效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10747058/