0

我试图将段落的每一行包装成一个跨度标签。到目前为止有效(感谢我找到的代码)。现在我正在尝试引入条件。我想要的是检查字符串(o 某行)是否包含某个文本或模式,如果是,我想操作输出。

var txt = $(".ym-col1 p.address").html().split("<br>")
var output = ""
for(var x=0;x<txt.length;x++) {
    if($("txt[x]:contains(\"08\")")) {
        output = output + "<span class=\'telephone\'>"+txt[x]+"</span><br>"
    }
        if($("txt[x]:contains(\"@\")")) {
        output = output + "<span class=\'email\'>"+txt[x]+"</span><br>"
    }

}
$(".ym-col1 p.address").html(output);

如果我只将输出与 if() 一起使用,它可以工作,但如果我将文本的每一行都加倍。任何想法我做错了什么?

还有一个问题。:) 有没有一种聪明的方法来检查一个字符串是否包含超过 5 个数字?(例如:123456)

4

2 回答 2

1

You are misusing jQuery in the if statements, you should use indexOf method of the String object:

$(".ym-col1 p.address").html(function(i, html){ 
     var txt = html.split('<br>'), output;
     for(var x = 0; x < txt.length; x++) {
         if ( txt[x].indexOf("08") > -1 ) 
             output += "<span class='telephone'>"+txt[x]+"</span><br>"
         else 
             output += "<span class='email'>"+txt[x]+"</span><br>"
     }
     return output;
})
于 2013-03-02T02:01:59.353 回答
0

The following code creates a jQuery object (aka a wrapped set):

$("txt[x]:contains(\"08\")")

It will always create a wrapped set, even if the wrapped set is empty, so the following conditional is always true:

if($("txt[x]:contains(\"08\")")) {

If you want to check if a wrapped set is not empty, you can use:

if($("txt[x]:contains(\"08\")").length > 0) {

But if what is between the <br> tags is just text, you shouldn't even be using a wrapped set. You could use something line this:

if (txt[x].indexOf("08") >= 0) {

and

if (txt[x].indexOf("@") >= 0) {
于 2013-03-02T02:02:56.977 回答