Jquery /javascript函数在firebug控制台中工作,但在页面加载时不起作用
jquery/javascript function work in the firebug console but not on page load
长话短说,我需要编辑一个文本区后,它是由一个wordpress插件,我可以设置id和默认值,但我不能设置事件或其他任何东西,我希望默认值消失后,用户点击输入电话号码。
我已经尝试了几种方法来做到这一点,没有运气,一些是:
<script type="text/javascript">
$(document).ready(function(){
// Your code goes here
function clearOnInitialFocus ("telid01") {
var clearedOnce = false;
document.getElementById("telid01").onfocus = (function () {
if (clearedOnce == false) {
this.value = '';
clearedOnce = true;
}
})
}
window.onload = function() { clearOnInitialFocus('telid01');}
});
</script>
也试过
<script type="text/javascript">
$(document).ready(function(){
document.getElementById('telid01').addEventListener('focus', function() {
this.value = "";
});
});
</script>
这在控制台中工作,但在页面加载时不起作用:
document.getElementById('telid01').addEventListener('focus', function() {
this.value = "";
既然你正在使用jQuery,你也可以使用jQuery的事件绑定,像这样:
$(document).ready(function(){
var clearedOnce = false;
$(this).on('focus', '#telid01', function () {
if (!clearedOnce) {
$(this).val('');
clearedOnce = true;
}
});
});
编辑:如果您将事件附加到'文档',然后将id作为选择器传递给on(),它应该工作,并且应该能够附加事件,即使没有页面上存在的字段。参见:http://api.jquery.com/on/
你以一种奇怪的方式使用函数参数。我试过下面的代码是基于你的,它工作得很好。
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// Your code goes here
var clearedOnce = false;
document.getElementById("myTest").onfocus =
function () {
if (clearedOnce == false) {
this.value = '';
clearedOnce = true;
}
};
});
</script>
</head>
<body>
<input id="myTest" value="placeholder" />
</body>
</html>
相关文章:
- 弹出加载不起作用
- GULP中的Ctrl+S之后,实时重新加载不起作用
- 影子盒加载不起作用
- 余烬 CLI 实时重新加载不起作用
- 在Javascript中保存和加载不起作用
- 路由到新页面时加载不起作用
- IE11 脚本加载不起作用(有时)
- 砌体图像加载不起作用
- Jquery 移动加载不起作用
- 在javascript/jquery中加载不起作用
- jquery瀑布插件's等待图像加载不起作用
- 简单的Jquery/Ajax加载不起作用
- 代码点火器&AJAX-Div重新加载不起作用
- HTML加载不起作用
- 有什么原因吗('img')加载不起作用(jQuery)
- 弹出加载不起作用
- 图像加载不起作用,错误Uncaught TypeError:类型错误
- 窗口加载不起作用
- 加载不起作用,但鼠标悬停正常工作
- 在wordpress中,ajax加载不起作用