2

您好,我正在尝试以动态方式发送 ID,代码如下:

function formsub(val){
    val2 = "form#" + val.toString() + " :input";
    val3 = "form#formmain :input";
    $(val3).each(function () {
        var input = $(this);
        alert($(this).val());
    });
}

当有人单击表单中的提交按钮时,这将调用formsub但我遇到的问题和错误:

Uncaught exception: Syntax error , unrecognized expression ''

我尝试使用val3它并且工作正常但是当我使用val2它时给我错误但它们是相同的值。

<form id='formmain' method='post' onsubmit='formsub(this.id)'>
    <label>Name</label>
    <input type='textbox' required />
    <span style='color:red;'>*</span>
    <br/>
    <label>Male</label>
    <input type='radio' required />
    <span style='color:red;'>*</span>
    <br/>
    <label>Female</label>
    <input type='radio' required />
    <span style='color:red;'>*</span>
    <br/>
    <input type='submit' />
    <br/>
</form>

上面的代码用于表单。

提前致谢

4

6 回答 6

3

As already mentioned by others and by me, the position of the colon is different in both strings and that's why you get the error in one case.

However, you can avoid the whole string concatenation if you work directly with the DOM element.

HTML:

<form id='formmain' method='post' onsubmit='formsub(this)'>

JS:

function formsub(ele){
    $(ele).find(':input').each(function () {
        // ...
    });
}

Even better if use jQuery to bind the event handler, e.g.:

$('form').on('submit', formsub);
// or $('#formmain').on('submit', formsub);

Inside the event handler, this will refer to the form element then. Learn more about event handling: http://learn.jquery.com/events/.

于 2013-06-12T11:38:46.713 回答
2

替换这个:

val2 = "form#" + val.toString() + ": input";  // form#formmain: input

有了这个:

val2 = "form#" + val.toString() + " :input";  // form#formmain :input

还有一个建议,因为ID应该是唯一的,所以您可以只使用 ID 而不是form#ID,例如:

val2 = "#" + val.toString() + " :input";      // #formmain :input

此外,您可以修改js,如:

function formsub(val) {
    val2 = "#" + val.toString() + " :input";
    val3 = "#formmain :input";
    $(val2).each(function () {
        alert(this.value);
    });
}
于 2013-06-12T11:31:41.117 回答
2

尝试使用

val2="form#"+val+" :input";

让我知道这有帮助吗?

于 2013-06-12T11:31:59.290 回答
2

当我分析代码时,我发现 val2 和 val3 之间存在细微差别:

用这个替换你的 val2:

val2="form#"+val.toString()+" :input";

因为你忘记了空间。

于 2013-06-12T11:32:07.310 回答
2

之间没有空格:input应该是:input

function formsub(val){
    val2="form#" + val.toString() + ":input"; // no space between : and input
    val3="form#formmain :input";
    $(val3).each(function(){
        var input = $(this);alert($(this).val());   
    });
}
于 2013-06-12T11:32:25.813 回答
1

尝试

$("form#" + val.toString() + ":input").each(function(){
 var input = $(this);  
 alert(input.val());
});
于 2013-06-12T11:30:10.950 回答