我希望将输入的电话号码传递到按钮上的 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/