[英]Updating/overwriting HTML data with jQuery?
I am trying to loop through response data and insert values them into the HTML of my webpage, the HTML might already contain some values so I want to clear them and insert only the new ones so it is up to date. 我正在尝试遍历响应数据并将其值插入到我的网页的HTML中,HTML可能已经包含一些值,因此我想清除它们并仅插入新值,以便它是最新的。
My HTML code looks like this; 我的HTML代码如下所示;
<div id="ind">
{% for inf in prospect.prospect_industries.all %}
{% if inf.is_interested %}
<div>
<span id="industryInterest" data-fit="id_industry{{inf.id}}"></span>
<p>{{inf.get_industry_display}}</p>
</div>
{% endif %}
{% endfor %}
</div>
My JS looks like this: 我的JS看起来像这样:
for (i = 0; i < response.length; i++) {
//alert(response[i].industry + ":" + response[i].is_interested);
if (response[i].is_interested) {
$("#industryInterest").html(response[i].industry);
$("#industryInterest").attr("data-fit", response[i].industry);
}
}
I tried to do something like this 我试图做这样的事情
$('#ind').html('');
however, that removes the HTML within the #ind div so then I am not able to insert the new values. 但是,这会删除#ind div中的HTML,因此我无法插入新值。 What is the correct approach to update the HTML in this case?
在这种情况下,更新HTML的正确方法是什么? Do I first clear the HTML of the #ind div and then recreate it from jQuery?
我首先要清除#ind div的HTML,然后从jQuery重新创建它吗?
I managed to get this working using the following code: 我设法使用以下代码使之工作:
$('#industryInterest').html("");
for (i = 0; i < response.length; i++) {
if (response[i].is_interested) {
$("#industryInterest").append("<p>" + response[i].industry + "</p>");
}
}
So, as we learned - using same id for multiple elements is not allowed. 因此,据我们了解-不允许对多个元素使用相同的ID。 Of course, you can add same ids, but your code
当然,您可以添加相同的ID,但是您的代码
$("#industryInterest")
will select only first one. 将仅选择第一个。
That's why you need to use something else. 这就是为什么您需要使用其他东西的原因。 Use a class
industryInterest
: 使用class
industryInterest
:
<span class="industryInterest" ....
Next, you want to update not all span
s but ones which are is_interested
. 接下来,您不希望更新所有
span
而是要更新is_interested
。 For getting element with certain index use eq
为了获得具有特定索引的元素,请使用
eq
So, your code becomes: 因此,您的代码变为:
for (i = 0; i < response.length; i++) {
//alert(response[i].industry + ":" + response[i].is_interested);
if (response[i].is_interested) {
// we use class here and we're getting
// element with the same index as i
// and you can chain jquery functions too!
$(".industryInterest").eq(i)
.html(response[i].industry)
.attr("data-fit", response[i].industry);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.