【问题标题】:jQuery append hrefs to mulitple words in divjQuery将href附加到div中的多个单词
【发布时间】:2014-12-21 11:40:57
【问题描述】:

我有一个带有类名 (.product) 的 div,我想做的是找到多个不同的单词,并为每个单词附加/替换它们为 href 链接或 span 等。

会有多个不同的单词要附加,因此很可能是 foreach 运行。

我已经尝试了下面的代码,但无法让它坚持下去,因为它只是替换了脚本中的整个最后一个单词变量。

jQuery('.product').each(function(){
var word1 = jQuery(this).text().replace(/word1/g,"<span>word1</span>");
jQuery(this).html(word1);
});

jQuery('.product').each(function(){
var word2 = jQuery(this).text().replace(/word2/g,"<span>word1</span>");
jQuery(this).html(word2);
}); 

如果 jQuery/JS 无法做到这一点,那么 php,我将如何扫描数据库文本区域值/内容并替换 foreach 变量(单词)并替换为 href 链接?

任何帮助将不胜感激。

干杯

【问题讨论】:

  • 能分享一下html吗
  • 你能提供一个示例输入和所需的输出吗?
  • 假设我有一个像这样的 div...
    测试 Ipsum 规则 britannia lorem 鱼和薯条 ipsum 去厕所欢呼队友松饼伴侣去酒吧美好的一天John harry potter 一杯茶 一杯茶饼。
    并且我想找到单词 test、harry..etc 并将链接附加到每个单词,但这些链接对于每个找到的单词都会有所不同。

标签: javascript jquery replace append


【解决方案1】:

你的尝试看起来不错,只是少了一点。与其更改 text 并将其推送到 HTML 中,不如尝试更改 HTML 中的文本并将 HTML 推回 ... 并将正确的 html 放入 (&lt;/span&gt;) ...

jQuery('.product').each(function(){
  var word1 = jQuery(this).html().replace(/word1/g,"<span>word1</span>");
  jQuery(this).html(word1);
});

jQuery('.product').each(function(){
  var word2 = jQuery(this).html().replace(/word2/g,"<span>word1</span>");
  jQuery(this).html(word2);
}); 

【讨论】:

    【解决方案2】:

    我想你想用&lt;span&gt; 标签包装单词。您可以使用带有函数重载的html 并用正则表达式替换单词来执行以下操作。 $0 表示匹配的单词。

    jQuery('.product').each(function() {
       $(this).html(function() {
          return $(this).text().replace(/\w+/g, "<span>$0</span>");
       });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      相关资源
      最近更新 更多