【问题标题】:Change the innerHTML of EVERY element with specified id更改具有指定 id 的每个元素的 innerHTML
【发布时间】:2013-03-30 21:21:37
【问题描述】:

我正在尝试更改 ID 为“文件名”的 每个 元素的 innerHTML 值,但只有第一个被更新。

我的问题是 只有第一个 id 为 'filename' 的元素被更新了。

HTML 代码是作为流动模板生成的,但我认为它不应该改变任何东西。

这是 HTML:

  <ul>
    {% for product in products %}
      <li>
      <p>{{ product.title }}</p>
      {% for image in product.images %}
        <img src={{ image.src }} height="200px" />
        <p>1) Is your image name descriptive? {{ image.src }}</p>
        <p>2) Is your alt tag descriptive enough? {{ product.title }}</p>
        <p>3) Is your image file type JPEG? <div id="filename">{{ image.src }}</div></p>
      {% endfor %}
      </li>
      <hr>
      {% endfor %}
    </ul>

还有 javascript:

<script type="text/javascript">
  $("#filename").each(function()  {
    $(this).html("ext!");
  });
</script>

【问题讨论】:

    标签: javascript jquery liquid


    【解决方案1】:

    ID's need to be unique - 你应该尝试用id="filename" 替换所有元素到class="filename",然后在你的each() 函数中用.filename 替换#filename,所以它类似于以下:

    $(".filename").each(function()  {
        $(this).html("ext!");
    });
    

    【讨论】:

    • 这实际上很有意义。谢谢! (除了分机,这不是错字,代表扩展,哈哈)