【问题标题】:Is possible to use replaceWith and replace in the same function?可以在同一个函数中使用replaceWith 和replace 吗?
【发布时间】:2021-08-04 06:26:36
【问题描述】:

我正在使用模板引擎,并以我能做到的唯一方式传递一个变量,但是这个变量的输出是一个数组,它出现在同一行中,没有中断。

<div>
  <h4>Questions</h4>
  <span id="question">
     How was your day?,Could you finish it?
  </span>
</div>

所以这就是它的外观,我不能简单地编辑 span 文本,如果渲染后不查看它,我的 span 内部代码是空的。

我想做这样的事情:

$( "#question" ).replaceWith(  this.text().replace(/,/g, '<br>')); 

这可能吗?

【问题讨论】:

  • 您确定要使用replaceWith()吗?这将删除 question 跨度,以便文本直接位于 &lt;div&gt; 中。

标签: javascript jquery arrays performance


【解决方案1】:

您需要使用回调函数将this 设置为您要替换的元素。

另外,this 是一个 DOM 元素,您需要将其包装在 jQuery 对象中才能使用text() 方法。

$("#question").replaceWith(function() {
  return $(this).text().replace(/,/g, '<br>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <h4>Questions</h4>
  <span id="question">
     How was your day?,Could you finish it?
  </span>
</div>

【讨论】:

    【解决方案2】:

    虽然您可以再次引用 #question 来检索文本:

    $("#question").replaceWith($('#question').text().replace(/,/g, '&lt;br&gt;'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>
      <h4>Questions</h4>
      <span id="question">
    How was your day?,Could you finish it?
                                </span>
    </div>

    我有点怀疑这就是你想要的,因为它会彻底摧毁#question

    <div>
      <h4>Questions</h4>
    How was your day?<br>Could you finish it?                         
    </div>
    

    如果要保留#question,只需更改其内容,使用.html,而不是replaceWith

    const q = $("#question");
    q.html(q.text().replace(/,/g, '<br>'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>
      <h4>Questions</h4>
      <span id="question">
    How was your day?,Could you finish it?
                                </span>
    </div>

    【讨论】:

    • 你为什么说它完全破坏了#question?因为它有效,但仅适用于渲染的第一个文件。
    • 查看我的答案中的 HTML 块 - 看看 #question 现在是如何消失的?它已被完全替换,这听起来并不完全像人们想要的那样(但如果你对它没问题,那很好)。重复的 ID 是无效的 HTML,因此如果您有多个具有相同 ID 的元素,您应该首先修复它,然后遍历新选择器的元素,无论它是什么。
    【解决方案3】:

    如果你想保持跨度,请使用html(function)

    $("#question").html((i, curr) =&gt; curr.replace(/,/g, '&lt;br&gt;'));
    #question{ color: green}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>
      <h4>Questions</h4>
      <span id="question">
    How was your day?,Could you finish it?
      </span>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-26
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 2021-06-06
      • 2020-11-01
      相关资源
      最近更新 更多