将参数从输入传递给onclick方法

时间:2018-11-02 09:19:29

标签: javascript jquery input

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

我怎么会这样。

taskToStorage

以下返回null

3 个答案:

答案 0 :(得分:1)

代码存在问题是因为您在提供给#的{​​{1}}值上有id前缀。那应该删除。

但是,应该指出的是,使用不引人注目的事件处理程序而不是内联事件处理程序是更好的做法。其次,由于您要获取的getElementById()的值为input,因此在事件发生时从DOM读取其值会更容易。当您使用jQuery标记问题后,下面是使用该示例的示例:

id
$('#call').on('click', function() {
  var phone = $('#phone').val();
  
  console.log(phone);
});

是否需要它,这是普通的JS等效项:

<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" />
document.getElementById('call').addEventListener('click', function() {
  var phone = document.getElementById('phone').value;
  console.log(phone);
});

答案 1 :(得分:0)

将选择器中的IOException删除为#,默认情况下会将参数值视为getElementById()。然后在函数内使用传递的元素的id属性:

value
function callCustomer(el){
  console.log(el.value);
}

答案 2 :(得分:0)

function callCustomer(id)
{
//Javascript
 console.log(id.value);
//or
 console.log(document.getElementById('phone').value);
 //or  --Jquery
  console.log($('#phone').val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<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">

尝试