javascript - 将参数从输入传递到 onclick 方法

标签 javascript jquery input

我希望将输入的电话号码传递到按钮上的 callCustomer() 函数中。

我怎么会得到这个。

<button onclick="callCustomer(document.getElementById('#phone'))" type="button" name="call" id="call" class="btn btn-primary btn-lg call-customer-button">
  <span class="glyphicon glyphicon-earphone" aria-hidden="true"></span>
                  Call customer
</button>

<input type="text" id="phone" name"phone">

以下返回null

最佳答案

您的代码的问题是因为您在提供给 getElementById()id 值上有 # 前缀。那应该被删除。

但是应该注意的是,使用不显眼的事件处理程序而不是内联事件处理程序是更好的做法。其次,由于您尝试获取其值的 input 具有 id,因此在事件发生时从 DOM 中读取其值会更容易。当您使用 jQuery 标记问题时,下面是一个使用它的示例:

$('#call').on('click', function() {
  var phone = $('#phone').val();
  
  console.log(phone);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" name="call" id="call" class="btn btn-primary btn-lg call-customer-button">
  <span class="glyphicon glyphicon-earphone" aria-hidden="true"></span>
  Call customer
</button>

<input type="text" id="phone" name "phone" value="07777 777 777" />

如果你需要它,这里是普通的 JS 等价物:

document.getElementById('call').addEventListener('click', function() {
  var phone = document.getElementById('phone').value;
  console.log(phone);
});
<button type="button" name="call" id="call" class="btn btn-primary btn-lg call-customer-button">
  <span class="glyphicon glyphicon-earphone" aria-hidden="true"></span>
  Call customer
</button>

<input type="text" id="phone" name "phone" value="07777 777 777" />

关于javascript - 将参数从输入传递到 onclick 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53115736/

相关文章:

javascript - 为什么 {10 + '1' } + 10 等于 10?

Javascript - 停止表单提交,self.submit 不是函数

javascript - 从 C# 生成 JQuery (MVC 5 - Razor)

javascript - 在javascript中是否可以将算术操作数分配给变量?

javascript - 什么 app.set 功能(express.js)?

javascript - 如何从缓存或ajax加载中返回模板?

jQuery - 如果未选择单选按钮则运行函数/代码

CSS提交输入黑边

python如果用户输入包含字符串

c - 使用键盘中断显示与用户键入内容不同的内容