[英]Having 2 actions occur on button click javascript
我不太了解 javascript,我正在尝试提取表单的输入值,构建链接以将值传递给并在单击按钮时将用户发送到该链接。
我不确定如何使这两个动作发生 onClick。
这是我目前拥有的:
<script>
function myFunction() {
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var link = 'https://app.squarespacescheduling.com/schedule.php\?owner=21917237&appointmentType=20129186&firstName=' + firstname + '&lastName=' + lastname + '&email=' + email + '&phone=' + phone;
}
</script>
这就是我正在尝试与我的按钮元素内联的内容:
<div class="de elBTN elAlign_center elMargin0 ui-droppable de-editable" id="tmp_button-86409" data-de-type="button" data-de-editing="false" data-title="button" data-ce="false" data-trigger="none" data-animate="fade" data-delay="500" style="margin-top: 30px; outline: none; cursor: pointer; display: block;" aria-disabled="false" data-elbuttontype="1">
<a onclick={myFunction(), onclick="location.href=link;"} class="elButton elButtonSize1 elButtonColor1 elButtonRounded elButtonPadding2 elBtnVP_10 elButtonCorner3 elBtnHP_25 elBTN_b_1 elButtonShadowN1 elButtonTxtColor1 elButtonFull" style="color: rgb(255, 255, 255); font-weight: 600; background-color: rgb(1, 116, 199); font-size: 26px;">
<span class="elButtonMain"><i class="fa_prepended fa fa-angle-double-right"></i>Let's Get Started<i class="fa_appended fa fa-angle-double-left"></i></span>
<span class="elButtonSub"></span>
</a>
</div>
我需要将用户发送到在 var link 中创建的链接。 发生这种情况的最佳方法是什么?
谢谢!
将动作组合在一个 function 中可以满足您的需要。
//function declaration
<script>
function myFunction() {
var baseUrl = 'https://app.squarespacescheduling.com/schedule.php\owner=21917237&appointmentType=20129186'
var data = {
firstname: document.getElementById("firstname").value, //if using ts, can add ? for checking the existence of ```document.getElementById('firstname')?.value
lastname: document.getElementById("lastname").value,
email: document.getElementById("email").value,
phone: document.getElementById("phone").value,
}
//do some checking
var unvalidElem = Object.values(data).filter(eachValue => eachValue !== undefined || eachvalue !== null)
//if all elements valid, then go to the link
if(unvalidElem.length === 0){
location.href = `${baseUrl}&firstName=${firstname}&lastName=${lastname}&email=${email}&phone=${phone}`
}
</script>
//actually invoke
<a onclick={myFunction();"}
在您构建 url 后,将其添加到 function 的底部:
location.href = "yourUrl";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.