Selecting numbers with jQuery

北战南征 提交于 2021-02-18 08:22:27

问题


In a given DIV I wish to apply a SPAN to all numbers and only them. Is there a way to select numbers with jQuery ?


回答1:


jQuery doesn't provide native selectors for text, but it is possible to achieve that effect. I adapted this from my answer to a previous question, designing it to not mangle any links with numbers in the URL (jsFiddle demo):

function autospan() {
    var exp = /-?[\d.]+/g;

    $('*:not(script, style, textarea)').contents().each(function() {
        if (this.nodeType == Node.TEXT_NODE) {
            var textNode = $(this);
            var span = $('<span/>').text(this.nodeValue);
            span.html(span.html().replace(exp, '<span class="foo">$&</span>'));
            textNode.replaceWith(span);
        }
    });
}

$(autospan);



回答2:


No, jQuery provides no selector functionality against text nodes...you can loop through the .contents() and manipulate textnodes as you want, but jQuery won't help much here.

For example:

$("div").html(function() { 
  return $(this).text().replace(/(\d+)/g,"<span>$1</span>"); 
});

You can test it out here, note that there are drawbacks to any approach like this, you're changing the .innerHTML which will destroy any event handlers, attached behaviors, etc. Only use this if the content is only text to begin with.




回答3:


You'd have to use regular old javascript. Perhaps use a regular expression to find all numbers and replace them with span tags wrapped around them.

var str = "some text 123"
str = str.replace(/(\d+)/g, "<span>$1</span>");

you'd replace "str" with the contents of some elements. So let's say you wanted to do this over all

elements in your page

$('p').each(function(){ 
    var str = $(this).text();
    str = str.replace(/(\d+)/g, "<span>$1</span>"); 
    $(this).text(str);
 }

edit: you all type too fast



来源:https://stackoverflow.com/questions/4059985/selecting-numbers-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!