Jquery /javascript函数在firebug控制台中工作,但在页面加载时不起作用

jquery/javascript function work in the firebug console but not on page load

本文关键字:加载 不起作用 javascript 函数 firebug Jquery 控制台 工作      更新时间:2023-09-26

长话短说,我需要编辑一个文本区后,它是由一个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>