我正在为我正在设计的 web 应用程序使用 jquery 的 .replaceWith() 函数。我的 HTML 是这样的:
{% for service in services %}
<div id="service" name="name" value="{{service.name}}">
{{service.name}} <a href='main/name/{{service.name}}'> Click if you want to see more </a>
<div id="rating_services">
<form name="rating">
{% csrf_token %}
<input name="star1" id="star_1" type="radio" class="star" value="1"/>
<input name="star1" id="star_2" type="radio" class="star" value="2"/>
<input name="star1" id="star_3" type="radio" class="star" value="3"/>
<input name="star1" id="star_4" type="radio" class="star" value="4"/>
<input name="star1" id="star_5" type="radio" class="star" value="5"/>
<input type="submit" class="button" id="submit_btn" value="Rate this agency!">
</form>
{% endfor %}
</div>
我的 JavaScript 是这样的:
$(function()
{
$(".button").click(function()
{
$('#rating_services').replaceWith("<div id='thanks'> Thanks! </div>");
}
});
我想做的是用户是否评价。显示感谢而不是评级。但是,该信息是在 for 循环内显示的(用于显示多个“机构”)。所以,我只能一一评价,一次评价一个。我该如何更改它以便我可以乱序评分?我尝试将 div id
更改为 {{forloop.counter}}
,但是 javascript 可以处理 #
和 { {forloop.counter}}
。有什么建议么?
最佳答案
我认为你有多个div
循环结果的 ID 为“rating_services”?
如果是这样,则不要硬编码 div
的 ID如果你想替换,你应该给每个div
s 一个类(即 class="rating_services"
而不是 id="rating_services"
),然后检索 div
动态地使用 jQuery closest()
函数如下:
$(function()
{
$(".button").click(function()
{
$(this).closest('.rating_services').replaceWith("<div id='thanks'> Thanks! </div>");
}
);
});
有关closest()函数的更多信息请参见此处: http://api.jquery.com/closest/
关于javascript - .replaceWith jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13223942/