制作外部Javascript
我有这个密码。这是工作,但我需要使脚本文件外部。我想创建另一个文件sample.js,其中是占位符的脚本文件。我尝试将其设置为外部,但不知道如何调用脚本中使用的函数 这是带有内部脚本的html文件制作外部Javascript,javascript,html,Javascript,Html,我有这个密码。这是工作,但我需要使脚本文件外部。我想创建另一个文件sample.js,其中是占位符的脚本文件。我尝试将其设置为外部,但不知道如何调用脚本中使用的函数 这是带有内部脚本的html文件 <!DOCTYPE html> <html> <head> </head> <body> <input type="text" placeholder="
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="text" placeholder="sample" id="sample2">
<script type="text/javascript">
function hasPlaceholderSupport() {
var input = document.createElement('input');
return ('placeholder' in input);
}
if(!hasPlaceholderSupport()){
var inputs = document.getElementsByTagName('input');
for(var i=0, count = inputs.length;i<count;i++){
if(inputs[i].getAttribute('placeholder')){
inputs[i].style.cssText = "color:#939393;font-style:italic;"
inputs[i].value = inputs[i].getAttribute("placeholder");
inputs[i].onclick = function(){
if(this.value == this.getAttribute("placeholder")){
this.value = '';
this.style.cssText = "color:#000;font-style:normal;"
}
}
inputs[i].onblur = function(){
if(this.value == ''){
this.value = this.getAttribute("placeholder");
this.style.cssText = "color:#939393;font-style:italic;"
}
}
}
}
}
</script>
</body>
</html>
函数haspholdersupport(){
var input=document.createElement('input');
返回(输入中的“占位符”);
}
如果(!haspholdersupport()){
var inputs=document.getElementsByTagName('input');
对于(var i=0,count=inputs.length;i,根据您的评论
HMTL文件haspholderSupport();
不能在同一标记中同时包含外部脚本引用和内部脚本
改变
<script src="sample.js"> hasPlaceholderSupport();</script>
haspholdersupport();
到
haspherentsupport();
但重要的部分是您必须将其放在页面末尾,就在
标记之前。否则,对getElementById
的调用将找不到任何内容
否则,您需要实现“文档就绪”代码(如果您使用的是jQuery,类似于$(function(){…});
您确定这不仅仅是
的问题吗?“它不起作用”它以什么方式不起作用?您是否在控制台等中看到任何错误?您能否显示外部脚本的确切内容,以及用于包含它的
标记?它不起作用-您可以使用的最无用的短语。什么不起作用?它不起作用?它在做什么?它不应该做什么?您明白吗您的浏览器开发人员工具中是否存在控制台错误?请帮助我们提供帮助you@Styxes向我们展示您是如何将其作为外部脚本包含的。我的猜测是您将其作为资源放在了
中,因此它在DOM准备就绪之前运行,而不是现在的位置。但这只是一个猜测-没有看到您实际尝试了什么,我们不知道。
<script src="sample.js"></script>
<script>hasPlaceholderSupport();</script>