【问题标题】:How do I set the text of a child DIV inside a repeater?如何在中继器中设置子 DIV 的文本?
【发布时间】:2009-07-30 15:19:36
【问题描述】:

我有一个包含以下 HTML sn-p 的中继器:

<div id='parent'>
    <div id='child1'/>
    <div id='child2'>
         <script type="text/javascript" src="script.js"></script>
    </div>
</div>

我想使用 script.js 中的函数选择标记为“父”的 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>

我如何使用 jQuery 做到这一点?

【问题讨论】:

  • 你想让&lt;div id=parent&gt;变成&lt;div id=child1&gt;还是&lt;div id=parent&gt;&lt;div id=child1&gt;&lt;/div&gt;
  • 我的最终 html 应该如下所示:
    这个内部文本是由 jQuery 设置的

标签: jquery repeater innerhtml


【解决方案1】:

首先,您不能在转发器中以这种方式编写 HTML。您不能将相同的 ID 分配给页面上的多个元素。您的 HTML 将需要使用类进行识别,如果您要识别它们的话。

<div class="parent">
  <div class="child1"><div>
  <div class="child2">Click Me<div>
</div>

脚本标签中的函数无法知道它们在 DOM 中相对于其他所有内容的位置。您需要将函数调用绑定到某个元素,以便能够导出与其相关的 DOM 关系。最简单的方法是使用 jQuery(或其他框架)向元素添加一些处理程序。

$(function() {
    $('.child2').click( function() {
        $(this).parent().find('.child1').html( 'some html' );
    });
});

上面将为每个带有child2类的DIV添加一个点击处理程序,当它被点击时,会发现它是父DIV(注意该类在父级上是不必要的),然后是正确的子级,其HTML要更新在它的课上。 另外,请注意,上面的脚本只需要添加到页面一次,而不是每个转发器项目一次。

【讨论】:

  • 好的.. 我可以让这个函数在 onload() 处运行吗?
  • 是的。实际上,正如它所写的那样,它会在加载 DOM 时运行。这就是 $(function() { ... }); 语法的作用。
【解决方案2】:
$('#parent').children('#child1').html('html goes here');

【讨论】:

    【解决方案3】:

    你的问题没有多大意义。你可以这样做:

    $("#child1").html("blah");
    

    您不需要引用 #parentthis

    但假设情况并非如此,您可以通过多种方式找到相对于this 的元素:

    $(this).children("#child1")
    

    $(this).find("#child1") // descendant, not just child
    

    $("#child1", this) // descendant, not just child
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多