javascript 如何通过单击按钮刷新 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28327932/
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
How can I refresh a div with a button click?
提问by Hunnenkoenig
I have this ajax call. It populates my page when opened. How can I reload it again for a new query by clicking a button?
我有这个ajax调用。打开时它会填充我的页面。如何通过单击按钮为新查询重新加载它?
I tried to figure it out myself, but I can't.
我试图自己弄清楚,但我不能。
Script:
脚本:
$(document).ready(function() {
$("#loading").show();
$.getJSON("listapps.php",function(data) {
$.each(data, function(i,data) {
data.title = data.title.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-').replace(/-+/g,'-');
if (data.title =='' | data.title =='-') {
data.title = 'App';
}
var div_data = "<div ><a href='"+data.title+"-"+data.appID+"'><img src='"+data.icon+"'></img></a></div>";
$(div_data).appendTo("#iconsfree");
});
$("#loading").hide();
});
return false;
});
HTML:
HTML:
<div id='loading'>Loading...</div>
<div id='iconsfree'></div>
采纳答案by Artur Filipiak
Make a method, call it when page is opened and on button click.
制作一个方法,在打开页面并单击按钮时调用它。
Script:
脚本:
$(document).ready(function() {
function refresh(){
$("#loading").show();
$.getJSON("listapps.php",function(data) {
var div_data = '';
$.each(data, function(i,data) {
data.title = data.title.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-').replace(/-+/g,'-');
if (data.title =='' | data.title =='-') {
data.title = 'App';
}
div_data += "<div ><a href='"+data.title+"-"+data.appID+"'><img src='"+data.icon+"'></img></a></div>";
});
$("#iconsfree").html(div_data);
$("#loading").hide();
});
}
// call the method on button click:
$(document).on('click', '#button', function(e){
e.preventDefault();
refresh();
});
// call the method when page is opened:
refresh();
});
回答by Patrick Moore
Attach it to the click()
event of some element.
将其附加到click()
某个元素的事件。
Your HTML:
你的 HTML:
<a id="button" href="#">Reload</a>
Your JavaScript:
你的 JavaScript:
$(document).ready( function(){
$("#button").click( function(){
$("#loading").show();
$.getJSON("listapps.php",function(data) {
$.each(data, function(i,data) {
data.title = data.title.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-').replace(/-+/g,'-');
if (data.title =='' | data.title =='-') {
data.title = 'App';
}
var div_data =
"<div ><a href='"+data.title+"-"+data.appID+"'><img src='"+data.icon+"'></img></a></div>";
$(div_data).appendTo("#iconsfree");
});
$("#loading").hide();
});
return false;
});
});