如何用jQuery替换父div的内容
我有这个 html 代码:
<div id="ht_key" class="ht_all">
<div class="ht_bottom">
<div class="ht_bottom_p">
<span class="ht_bottom_o">
<a href="javascript:;" onclick="htrc('key');\">click</a>
</span>
</div>
</div>
</div>
此代码可能会在页面中出现 5-6 次(或更多)。 我想从 htrc 函数中将 #ht_key div 替换为其他一些内容。 (“密钥”在每种情况下都不同)。问题是,如果页面中有 2 个具有相同“key”的 div,那么当 htrc 函数发生时,只有第一个 #ht_key div 被替换。因此,由于我需要替换单击 a(从中调用 htrc 函数)的 #ht_key div 的内容,有没有办法替换其父 div(具有 id 的父 div)?
我尝试过父级和最接近的,但没有一个返回结果。您有什么建议吗?
谢谢!
i have this html code:
<div id="ht_key" class="ht_all">
<div class="ht_bottom">
<div class="ht_bottom_p">
<span class="ht_bottom_o">
<a href="javascript:;" onclick="htrc('key');\">click</a>
</span>
</div>
</div>
</div>
This code may be seen in the page 5-6 times(or more).
I want from the htrc function to replace the #ht_key div with some other content. ("key" is different in each case). The problem is that if in the page there are 2 divs with same "key" then when the htrc function takes place, then only the first #ht_key div is replaced. So since i need to replace the content of the #ht_key div where the a (from which the htrc function is called) was clicked, is there any way to replace its parent div(the parent div which has id)?
I have tried both parent and closest but none of these returned the result. Do you have any suggestion?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的建议是将
ht_key
设为class
而不是id
。这样你的 HTML 就有效了。
或者更改
onclick
以传递this
,并执行closest()
直至ht_all
:js
如果您采用这种方法,我会为
ht_key
使用 HTML5data-
属性:如果您使用的是最新版本的 jQuery,你可以这样做:
My suggestion would be to make the
ht_key
aclass
instead of anid
.This way your HTML is valid.
Or change the
onclick
to passthis
, and do aclosest()
up toht_all
:js
If you take this approach, the I'd use a HTML5
data-
attribute for theht_key
:And if you're using the latest versions of jQuery, you can do:
我假设 #ht_key 实际上是锚点的父级(在这种情况下,您的代码片段中缺少结束标记)。我将删除“onclick”并绑定事件处理程序,如下所示:
I assume #ht_key is actually a parent for an anchor (in which case you are missing closing tag in your snippet). I would remove "onclick" and bind the event handler like this: