首页 > 解决方案 > 如何对单个 HTML 页面中的表单元素使用 OR (||)

问题描述

需要将多个javascript函数缩短(编译)为一个函数

我(未成功)尝试将表单元素分配给变量并将其回调。我还是很新……对不起!

<script type="text/javascript">
function confSubmit1()
{
    if(!document.getElementById("terms1").checked)
    { 
        alert("Please read and accept the Terms and Conditions");
        return false;
    }
    alert("You are now being redirected to PayPal");
    return true;    
}
function confSubmit2()
{
    if(!document.getElementById("terms2").checked)
    { 
        alert("Please read and accept the Terms and Conditions");
        return false;
    }
    alert("You are now being redirected to PayPal");
    return true;    
}
</script>

所以,我在一个 HTML 页面上有多个表单,所有这些都是通过 PayPal 购买的。每个表单都有一个复选框,供用户根据他们购买的产品同意条款。

我曾尝试使用变量等将上述代码缩短为单个函数,但我终其一生都无法弄清楚!

我确信有一种方法可以使用 OR (||) 语句(或其他方式)将所有这些都放入一个函数中,而无需为每个表单提供一个函数。我让它像这样工作,但似乎有更好的方法来做到这一点。

谢谢你。

标签: javascript

解决方案


function confSubmit(id)
{
   var check = document.getElementById(id).checked;
   check ? alert("You are now being redirected to PayPal") : alert("Please read and accept the Terms and Conditions"); 
   return check;
}
<form action="#">
	<input type="checkbox" id="checkb1"> Check1
	<input type="submit" value="submit" onClick="return confSubmit('checkb1')" />
</form>

<form action="#">
	<input type="checkbox" id="checkb2"> Check2
	<input type="submit" value="submit" onClick="return confSubmit('checkb2')" />
</form>

希望它会帮助你。


推荐阅读