仅在单个页面中运行字符计数javascript函数

Run character count javascript function in single page only

本文关键字:javascript 函数 字符 运行 单个页      更新时间:2023-09-26

我有一个可以编辑信息的页面。我写了一个简单的javascript代码,以便在加载此页面后立即计算字符数。所以我放了<body onload='charCount()'>。它工作得很好,但问题是当加载其他页面时,我得到了javascript错误:无法从元素id=title中获取值。我的整个网站使用相同的页眉和页脚,正文标记在页眉中。

有没有办法只在那个特定的页面上运行这个javascript?我也试着放<form onload='charCount()'>,但没有成功。

这是我的html页面:

<html>
<body onload='charCount()'>
....//end header section
<form>
<input id='title' type='text' value='abcd'/>
<div id='showcharcount'></div>
</form> //end content section
<script>
function charCount(){
var x = document.getElementById("title").value;
document.getElementById("showcharacount").innerHTML = charCountFunc(x) + "/35   characters allowed";
}
function charCountFunc(x) {
var n = x.length;
return n;
}
</script>
</body>
</html> //end footer section

好吧,如果你想在一个页面上运行脚本代码,而不是在其他页面上,你可以确保脚本只附加到所述页面。不在其他页面上,因为这将是垃圾的一部分,代码没有被使用。

您可以使用window.onload = functionName;命令,该命令在加载页面时调用函数functionName()

只需在要使用函数的网页上添加下一个脚本。

<script>
    function charCount(){
        ...
    }
    function charCountFunc(x) {
        ...
    }
    window.onload = charCount;
</script>

这可以在服务器端完成,方法是在显示表单的模板中添加上述片段。

您可以通过首先检查元素的存在来避免错误。

function charCount(){
    var elem = document.getElementById("title");
    if (elem != null) {
        var x = elem.value;
        document.getElementById("showcharacount").innerHTML = charCountFunc(x) + "/35   characters allowed";
    }
}