1

我有这个 jQuery 代码:

jQuery( document ).ready( function( $ ) {
$('#myform').submit( function() {

    if ($('#myform input').is(':checked')) {

    } else {
        //alert('Checkbox is not checked!!');
        window.location.replace("http://example.com/product-comparisons/?product-skus=0");

    }

 });

});

我想重定向到这个 URL:

http://example.com/product-comparisons/?product-skus=0

如果用户单击没有任何选中项的复选框。

我根据这个建议尝试了上面的代码:如何在 JavaScript/jQuery 中重定向到另一个网页?

但这行不通。我将不胜感激任何意见和建议。谢谢!

更新:这是我的 HTML 代码/表单:

<form action="/product-comparison/" id="myform">
<ul>
<li>
<input type="checkbox" name="product-skus[]" value="1" id="mycheckbox">
<a href="http://example.com/product/translator/">Translator</a>100<img width="150" height="150" title="View product" style="" alt="View product" class="attachment-thumbnail" src="http://example.com/wp-content/uploads/2012/12/pic1-150x150.jpg"></li>
<li><input type="checkbox" name="product-skus[]" value="2" id="mycheckbox">
<a href="http://example.com/product/arrows/">Arrows</a>120<img width="150" height="150" title="View product" style="" alt="View product" class="attachment-thumbnail" src="http://example.com/wp-content/uploads/2012/12/pic2.jpg"></li></ul>

<input type="submit" value="Compare">

</form>

但是我相信我的选择器是正确的,因为这个诊断代码(使用警报来确保 jQuery 漏斗到正确的逻辑)是完美的工作:

jQuery( document ).ready( function( $ ) {
$('#myform').submit( function() {

    if ($('#myform input').is(':checked')) {
        alert('Checkbox is checked, do nothing');
    } else {

        alert('Checkbox is not checked!!, do the redirects');


    }

 });
});
4

2 回答 2

0

如果您提交表单,您将提交到另一个文件。这意味着为了到达另一个位置,您可以设置它并document.location.replace取消表单提交(return false;应该足够了)

或者您操纵表单的操作(目标网址)。积极的副作用是,输入到表单中的任何数据实际上都会在两种情况下提交(默认操作和备用操作)

于 2012-12-10T08:42:11.973 回答
-1

试试下面的。在重定向后添加一个 return false :

jQuery(文档).ready(函数($){$('#myform').submit(函数(){

if ($('#myform input').is(':checked')) {

} else {
    //alert('Checkbox is not checked!!');
    window.location.replace("http://example.com/product-comparisons/?product-skus=0");
    return false; //Add this
}

}); });

于 2012-12-10T06:59:33.113 回答