简体   繁体   English

Javascript onclick 在页面加载时触发

[英]Javascript onclick fires on page load

Just starting out with front end development here, but despite my assuredly poor practices I've been enjoying things a lot.刚刚开始在这里进行前端开发,但尽管我的实践确实很糟糕,但我一直很享受。 Basically I'm trying to add an onclick function to an element when the page loads.基本上,我试图在页面加载时向元素添加一个onclick函数。 It was working fine as:它工作正常:

$("li a:contains('Search')").ready(function(){
    $("li a:contains('Search')").on("click", function(){
$("li a:contains('Search)").text("test")});
});

But my programmer spidey-senses were strongly activated by the quite frankly gross state of this code, so I tried to refactor and my thought for the easiest first-step refactoring was this:但是我的程序员的蜘蛛侠感觉被这段代码的相当粗糙的状态强烈激活,所以我尝试重构,我对最简单的第一步重构的想法是这样的:

function replaceWithSearch(element){
    element.text("test");
}

$("li a:contains('Search')").ready(function(){
    $("li a:contains('Search')").on("click", replaceWithSearch($("li a:contains('Search')")));
});

However, when I changed to that, the onclick function now launches immediately.但是,当我更改为那个时, onclick功能现在会立即启动。 Is there a way to force the function to only be evaluated when called as a callback?有没有办法强制函数仅在作为回调调用时才被评估? I would prefer to have the function be reusable, also if you have any other comments on refactoring my code or best practices I would be very glad to hear them.我更希望该函数可以重用,如果您对重构我的代码或最佳实践有任何其他意见,我会很高兴听到它们。 Again, just starting out with Javascript and I would love to build some good practices.同样,刚开始使用 Javascript,我很想建立一些好的做法。

Optimized code:优化代码:

$(document).ready(function() {
    $("li a:contains('Search')").bind("click", function() {
        $(this).text("test");
    });
});

If you prefer to use a function, proper way is:如果您更喜欢使用函数,正确的方法是:

$(document).ready(function() {
    $("li a:contains('Search')").bind("click", replaceWithSearch);
});

And in the function you don't have to use argument:在函数中,您不必使用参数:

function replaceWithSearch(){
    $(this).text("test");
}

Live test case .现场测试用例

If your elements are created after page load, use the .on() like this:如果您的元素是在页面加载后创建的,请像这样使用.on()

$(document).on("click", "li a:contains('Search')", replaceWithSearch);

Updated fiddle .更新了小提琴

Wrap the handler in a function like:将处理程序包装在如下函数中:

$("li a:contains('Search')").ready(function(){
    $("li a:contains('Search')").on("click", function() {replaceWithSearch($("li a:contains('Search')"))});
});

That way, the handler is defined and associated with the click event, rather than executing immediately.这样,处理程序被定义并与点击事件相关联,而不是立即执行。

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

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