使用 JQuery 将 HTML 插入 DIV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6618743/
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
Inserting HTML into DIV using JQuery
提问by rolling stone
I've got a bunch of buttons nested within div tags in my html
我有一堆按钮嵌套在我的 html 的 div 标签中
<div class="button-wrapper">
<button class="button-class">Click here</button>
</div>
<div class="button-wrapper">
<button class="button-class">Click here</button>
</div>
...
Clicking on the button posts some data using JQuery and returns some HTML through a .ajax success function. I'm trying to replace the content of the div for each button that is clicked, but for some reason my JQuery selector doesn't seem to be working.
单击按钮使用 JQuery 发布一些数据并通过 .ajax 成功函数返回一些 HTML。我正在尝试为单击的每个按钮替换 div 的内容,但由于某种原因,我的 JQuery 选择器似乎无法正常工作。
I'm trying the following within my success function:
我正在我的成功功能中尝试以下操作:
$(this).parent().html(data);
I know that the data is being posted successfully and that the success function is working. What's weird is that the following works:
我知道数据已成功发布并且成功功能正在运行。奇怪的是以下工作:
$(".button-wrapper").html(data);
but obviously this adds the HTML to every div, not just the one for the button that is clicked.
但显然这会将 HTML 添加到每个 div,而不仅仅是用于单击按钮的那个。
Does anyone know where I might be going wrong here?
有谁知道我在这里可能会出错?
回答by Justin Lucas
In jQuery 'this' is commonly overwritten within a callback. The workaround is to reference this using another variable:
在 jQuery 中,'this' 通常在回调中被覆盖。解决方法是使用另一个变量引用它:
var _this = this; //or var $_this = this;
$(_this).parent().html(data);
回答by James Montagne
The problem is that in your callback this
is not the button anymore. Try this:
问题是在您的回调this
中不再是按钮。尝试这个:
$(".button-wrapper").click(function(){
var that=this;
$.ajax(
// ...
success: function(data){
$(that).parent().html(data);
}
);
});
回答by Rejwanul Reja
This will helpfull for you....
这对你有帮助......
$("button").click(function(){
$("div").html("Hello <b>world</b>!");
});
回答by Kevin Bowersox
Html:
网址:
<div class="button-wrapper">
<button class="button-class">Click here</button>
</div>
<div class="button-wrapper">
<button class="button-class">Click here</button>
</div>
JS:
JS:
$.ajax({
//..
success: function(){
$(".button-class").click(function(){
$(this).parent().html("Dynamic Html");
});
}
});
回答by Younglegend
You should know that you need to load log of the success function eg: setInterval(myFunction,2500);
您应该知道您需要加载成功函数的日志,例如: setInterval(myFunction,2500);
回答by bevacqua
I'd recommend using firebug to tune your selector.
我建议使用 firebug 来调整您的选择器。
Other than that, can't you set unique IDs to each div?
除此之外,你不能为每个 div 设置唯一的 ID 吗?