问题描述
我有一个带有一个参数的通用JavaScript函数
I have a generic JavaScript function which takes one parameter
function foo(val) { ...}
我想在提交表单时调用函数
and I want to call the function when submit a form
<form>
<input type="text" id="formValueId"/>
<input type="button" onclick="foo(this.formValueId)"/>
</form>
但是表达式foo(this.formValueId)不起作用(并不感到惊讶,这是一次绝望的尝试),所以问题是,我如何将表单值传递给javascript函数。
正如我提到的JavaScript是通用的,我不想操纵其中的形式!
but the expression foo(this.formValueId) does not work (not surprised, it was a desperate attempt), So the question is, how can I pass a form value to the javascript function.As I mentioned the javascript is generic and I don't want to manipulate the form inside it!
我可以在中间创建一个帮助函数,用jQuery获取表单值(例如),然后调用函数,但我想知道如果没有帮助功能。
I could create a helper function in the middle to get the form values with jQuery (for example) and then call the function but I was wondering if I can do it without the helper function.
推荐答案
将内联点击处理程序取出可能会更清晰:
It might be cleaner to take out your inline click handler and do it like this:
$(document).ready(function() {
$('#button-id').click(function() {
foo($('#formValueId').val());
});
});
这篇关于如何将表单输入值传递给JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!