如何在转发器中设置子 DIV 的文本?
我有一个包含以下 HTML 片段的转发器:
<div id='parent'>
<div id='child1'/>
<div id='child2'>
<script type="text/javascript" src="script.js"></script>
</div>
</div>
我想使用 script.js 中的函数选择标记为“parent”的 div,并设置 ID 为“child1”的 div 的内部 HTML。
我的最终 html 应该如下所示:
<div id='parent'>
<div id='child1'>This inner text was set by jQuery</div>
<div id='child2'>
<script type="text/javascript" src="script.js"></script>
</div>
</div>
How do I do it using jQuery?
I have a repeater containing the following HTML snippet:
<div id='parent'>
<div id='child1'/>
<div id='child2'>
<script type="text/javascript" src="script.js"></script>
</div>
</div>
I would like to select the div tagged "parent" using a function inside script.js and set the inner HTML of the div with id "child1".
My final html should look like this:
<div id='parent'>
<div id='child1'>This inner text was set by jQuery</div>
<div id='child2'>
<script type="text/javascript" src="script.js"></script>
</div>
</div>
How do I do it using jQuery?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您不能在转发器中以这种方式编写 HTML 代码。 您不能将相同的 id 分配给页面上的多个元素。 如果您要识别它们,您的 HTML 将需要使用类来进行识别。
script 标签中的函数无法知道它们在 DOM 中相对于其他所有内容的位置。 您需要将函数调用绑定到某个元素,以便能够派生与其相关的 DOM 关系。 最简单的方法是使用 jQuery(或其他框架)向元素添加一些处理程序。
上面的代码将为每个带有
child2
类的 DIV 添加一个点击处理程序,当它被点击时,会找到它的父 DIV(注意,该类在父级上是不必要的),然后是正确的子 DIV,其 HTML 为根据其类别进行更新。 另请注意,上述脚本只需添加到页面一次,而不是每个转发器项目一次。First, you can't code your HTML this way in a repeater. You cannot assign the same ids to multiple elements on the page. Your HTML will need to use classes for identification, if you identify them at all.
Functions in the script tag have no way of knowing where they are in the DOM relative to everything else. You'll need to tie the function invocation to some element in order to be able to derive the relative DOM relationships to it. The easiest way is to use jQuery (or other framework) to add some handler to the elements.
The above will add a click handler to each DIV with class
child2
and when it is clicked, will find it's parent DIV (note that the class is unnecessary on the parent) and then the correct child whose HTML to update based on its class. Also, note that the above script only needs to be added to the page once, not once per repeater item.你的问题没有多大意义。 您可以这样做:
您不需要对
#parent
或this
的引用。但假设情况并非如此,您可以通过多种方式找到与
this
相关的元素:或
或
Your question doesn't make a lot of sense. You can just do this:
You don't need a reference to
#parent
orthis
.But assuming that wasn't the case, there are multiple ways you can find an element relative to
this
:or
or