如何在HTML中将函数作为参数传递



我是网络开发的新手,我提前道歉。我有一个表单,用户可以在其中写一条简单的消息,然后浏览器会打开whatsapp网页,其中包含之前写的消息。我需要将一个函数传递给动作="使之发挥作用的形式。我想不通。

到目前为止我尝试和工作的内容:

<form id="user_form" action="https://api.whatsapp.com/send?phone=123456789&text=Hello" method="post" enctype="text/plain">
<textarea id="msg" cols="30" rows="10" placeholder="Message ..."></textarea>
<input type="submit" value="connect us" class="btn">
</form>

它工作得很好,但我想要text参数(https://api.....text=VARIABLE)成为用户编写的消息。

我试过这样做,但似乎不起作用:

<form id="user_form" onSubmit="return sendMsg()" method="post" enctype="text/plain">
<textarea id="msg" cols="30" rows="10" placeholder="Message ..."></textarea>
<input type="submit" value="connect us" class="btn">
</form>
<script>
function sendMsg(){
var actualMsg = document.getElementById("msg").value;
document.user_form.action = "https://api.whatsapp.com/send?phone=123456789&text=Hello";
return false;
}
</script>

您需要的是一个更新action属性值的事件侦听器。

const url = 'https://api.whatsapp.com/send?phone=123456789&text=';
document.getElementById('msg').addEventListener('keyup', (e) => {
const val = (e.target.value === '') ? 'Hello guys' : e.target.value;
document.getElementById('user_form').setAttribute('action', url + val);
console.log(document.getElementById('user_form').getAttribute('action'));
})
<form id="user_form" action="" method="post" enctype="text/plain">
<textarea id="msg" cols="30" rows="10" placeholder="Message ..."></textarea>
<input type="submit" value="connect us" class="btn">
</form>

最新更新