繁体   English   中英

使用jQuery和Javascript更改DIV内容的功能不起作用

[英]The function to change the content of DIV with jQuery and Javascript is not working

单击按钮后,我将产生以下代码:

 <input type="submit" name="cancel" value="cancel" onclick="clear_form (); return false;" class="pure-button">

实际函数从文本区域中删除文本,并从表单中删除两个按钮:

 function clear_form () {
        $("#statement").val('');
        document.submitform.submit.value = "save";
        document.submitform.delete.remove();
        document.submitform.cancel.remove();
 }

但是,单击按钮(在Chrome中)时,会显示以下消息,并且clear_form函数不起作用。

Uncaught ReferenceError: clear_form is not defined 

有人知道为什么吗? 我错过了什么吗?

什么时候声明function clear_form() ...是在另一个函数内部声明的? 在这种情况下, clear_form()仅在包含函数的范围内本地可用。 在HTML属性中附加点击处理程序要求所提及的函数在全局范围内进行声明。

如果无法将clear_form()全局,则仍可以使用addEventListener()从Javascript添加本地函数,而不是在HTML中使用属性onclick 顺便说一句,这是在网站中用于分隔内容和逻辑的首选方式。

编辑

演示

Java脚本

function clear_form(){

    $("#statement").val('');
    document.submitform.submit.value = "save";
    document.submitform.delete.remove();
    document.submitform.cancel.remove();

    }

document.getElementById('submit').addEventListener('click',function(){

    alert()

    clear_form();

},false);

的HTML

<input type="submit" name="cancel" value="cancel" class="pure-button" id='submit'>

@cookiemonster所述 ,函数名称后的空格没有区别。

链接

我不确定您如何在完整的应用程序中使用该代码。 但我做了这个完整的工作示例页面

试试看,让我们知道它是否适合您。

请在head标签中这样:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function clear_form() {
            //    $("#statement").val('');  or load the JQuery Library and us this line
            document.submitform.statement.value = "";  // Used this instead of JQuery
            document.submitform.submit.value = "save";
            document.submitform.delete.remove();
            document.submitform.cancel.remove();
        }
    </script>

</head>
<body>
    <form name="submitform" id="submitform">
        <textarea id="statement" cols="30" rows="3"></textarea> <br />
        <input type="button" name="delete" value="delete" /><br />
        <input type="button" name="submit" value="Submit" /><br />
        <input type="submit" name="cancel" value="cancel" onclick="clear_form (); return false;" class="pure-button">
    </form>
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM