jQuery 在 document.ready 和 onClick 上运行一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16762675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run a function on document.ready and onClick
提问by Mr.Turtle
Is there a way to make this ajax-response run on document.ready, AND onClik without copy/paste the code in another function?
有没有办法让这个 ajax 响应在 document.ready 和 onClik 上运行而无需将代码复制/粘贴到另一个函数中?
$(document).ready(function() {
var ads = $('#ads').val();
function ajax(){
$.ajax({
url: "./services/finn_bilder.php",
type:"POST",
data:{ads: ads},
success:function(data){
$('#AdsDiv').html(data);
}
I want this to run onClick $('#id').click(function()); and the way its working now, without copy/paste?
我希望它运行 onClick $('#id').click(function()); 以及它现在的工作方式,没有复制/粘贴?
回答by Adam Tal
Just make sure you can reuse the javascript function you've created:
只要确保您可以重用您创建的 javascript 函数:
$(document).ready(function() {
// Will accure at document load
ajax();
// Will accure at every click
$(document).click(function() { ajax(); });
}
function ajax(){
var ads = $('#ads').val();
$.ajax({
url: "./services/finn_bilder.php",
type:"POST",
data:{ads: ads},
success:function(data){
$('#AdsDiv').html(data);
});
}
回答by Niccolò Campolungo
Just call it inside document ready and bind it to document.click.
只需在 document ready 中调用它并将其绑定到 document.click。
$(document).ready(function() {
var ads = $('#ads').val();
function ajax(){
$.ajax({
url: "./services/finn_bilder.php",
type:"POST",
data:{ads: ads},
success:function(data){
$('#AdsDiv').html(data);
}
});
}
ajax();
$(document).click(function() {
ajax();
});
}