【问题标题】:Problem "smartening" and link-parsing the same text问题“smartening”和链接解析相同的文本
【发布时间】:2011-04-10 04:43:54
【问题描述】:

我正在使用 jQuery,以及一个非常简单的脚本来用它们的“智能”对应物替换引号、撇号和双破折号:

function smarten(a) {
  a = a.replace(/(^|[-\u2014/(\[{"\s])'/g, "$1\u2018");      // opening singles
  a = a.replace(/'/g, "\u2019");                             // closing singles & apostrophes
  a = a.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1\u201c"); // opening doubles
  a = a.replace(/"/g, "\u201d");                             // closing doubles
  a = a.replace(/--/g, "\u2014");                            // em-dashes
  return a
  };

我将其用作TwitterJS 的回调,它解析链接并生成如下块:

<ul>
<li>Here's a link! <a href="http://www.foobar.com">http://www.foobar.com</a></li>
</ul>

问题是,如果我这样做:

$('#tweet li').html(smarten($('#tweet li').html()))

它会破坏链接,如果我这样做:

$('#tweet li').html(smarten($('#tweet li').text()))

它完全丢弃它们。 有没有一种智能、可靠的方法来只抓取文本(如果需要,也可以从 &lt;a&gt; 标签中提取),“smarten”,然后将其放回去,而不干扰 TwitterJS 的链接解析?

【问题讨论】:

    标签: javascript jquery twitter smart-quotes


    【解决方案1】:

    让我们做一个 jQuery 插件:

    jQuery.fn.smarten = (function(){
    
        function smartenNode(node) {
            if (node.nodeType === 3) {
                node.data = node.data
                    .replace(/(^|[-\u2014/(\[{"\s])'/g, "$1\u2018")
                    .replace(/'/g, "\u2019")
                    .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1\u201c")
                    .replace(/"/g, "\u201d")
                    .replace(/--/g, "\u2014");
            } else if (node.nodeType === 1) {
                if (node = node.firstChild) do {
                    smartenNode(node);
                } while (node = node.nextSibling);
            }
        }
    
        return function() {
            return this.each(function(){
                smartenNode(this);
            });
        };
    
    }());
    

    用法:

    $('#tweet li').smarten();
    

    【讨论】:

    • 谢谢!这似乎完美无缺! if-do-while 部分是常见的节点代码 sn-p 吗?不太明白。
    【解决方案2】:

    试试:

    $('#tweet li a').each( function() { $(this).text( smarten( $(this).text() ) ); } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-22
      • 2011-03-09
      • 2016-04-03
      相关资源
      最近更新 更多