Javascript中的HTML表单标签中的Javascript函数

Javascript within HTML form tag in the javascript function

本文关键字:Javascript 函数 表单 中的 HTML 标签      更新时间:2023-09-26

是否可以在HTML表单标签中放置JavaScript代码?我正在尝试实现这样的东西:

function abc(abcd) {
    document.getElementById("context").innerHTML += "<br> 1:";
    document.getElementById("context").innerHTML += "***<form METHOD=POST ACTION='"/InformationRetrieval/home'">***<input type='"checkbox'" name='" GoogleRelevance'" value='"1'"> Relevant <br><br>";
    document.getElementById("context").innerHTML += "<br> 2:";
    document.getElementById("context").innerHTML += "<input type='"checkbox'" name='" GoogleRelevance1'" value='"1'"> Relevant <br><br>";
    document.getElementById("context").innerHTML += "<br> 3:";
    document.getElementById("context").innerHTML += "<input type='"checkbox'" name='" GoogleRelevance3'" value='"1'"> Relevant <br>***<input type='"submit'" value='"Submit'"></form>***<br><br>";
}

在这个例子中我想问的是:我已经开始标签最初在我的开始2-3行,但我没有关闭它,而是插入一些更多的javascript行,最后我与另一个<input type="submit">关闭标签,但当我点击此按钮它不起作用。

我尝试使用OnClick属性,但也没有工作。

我被它难住了。

我认为你真的应该使用一些好的ajax库(jQuery, YUI, dojo, goog,…)来做这样的事情,把所有的代码都塞到表单属性中感觉不太对。正如nickf指出的那样,以这种方式修改dom属性确实不是一个好主意。因为我习惯了jQuery,这里是一个片段,我从你的帖子中理解的问题:

// Caching the stuff that you used to += on the innerHTML
var newStuff = ' /* your form code here */ '; 
jQuery
.ajax({
    url: /* your request to google */,
    context: jQuery('#context') // Caching the context dom node
})
.done(function() { 
    // The request was successful
    jQuery(this) // The cached context node is the context of this callback
    .append(newStuff); // You only have to append new stuff here, if you want something
                       // more dynamic insert the logic in this function
})
.fail(function() { /* alert("error"); */ })
.always(function() { /* alert("complete"); */ });

我没有测试过这个,这只是一个建议。对我来说,它更干净,它有一个优势,如果你让它在一个浏览器中工作,这样你就可以依靠jQuery来确保它在大多数其他浏览器中也能工作。

顺便说一下:你可以在整个html字符串周围使用单个',这样你就不需要逃避"的东西。

希望这有帮助,祝你好运!