功能内部功能

时间:2017-02-27 19:19:33

标签: javascript function

我不知道如何在功能中创建功能以及如何使用它。我创建了这样的smf。

function loadPage(nameBtn,URL,where){
$(nameBtn).click(function(){
    $.ajax({url: URL, success: function(result){
        $(where).html(result);
    }});
});
	function loadContent(where,content){
		$(where)[0].innerHTML = content;
	}
}
<script>

loadPage("#glowna-btn","cppages/cp.glowna.php","#Container-main").loadContent("#Menu-left-bar","lololollool");

</script>

1 个答案:

答案 0 :(得分:1)

好吧,当你编写一个函数并期望返回一个函数的调用时,你应该首先返回一些东西。在第二个代码块中,您希望 thing 成为一个对象,并定义方法loadContent

function loadPage(nameBtn, URL, where){
    $(nameBtn).click(function(){
        $.ajax({url: URL, success: function(result){
            $(where).html(result);
        }});
    });
    
    return {
        loadContent: function(where, content){
            $(where)[0].innerHTML = content;
        }
    };
}
<script>

loadPage("#glowna-btn", "cppages/cp.glowna.php", "#Container-main")
    .loadContent("#Menu-left-bar", "lololollool");

</script>

如果界面不重要,您只需返回一个函数并调用它(或将其存储在变量中,并随时调用)。

function loadPage(nameBtn, URL, where){
    $(nameBtn).click(function(){
        $.ajax({url: URL, success: function(result){
            $(where).html(result);
        }});
    });
    
    return function(where, content){
         $(where)[0].innerHTML = content;
    };
}
<script>
    loadPage("#glowna-btn", "cppages/cp.glowna.php", "#Container-main")
            ("#Menu-left-bar","lololollool");
</script>