1

为了试验,我四处游荡并尝试了一些正则表达式,我在 bestbuy.com 的控制台上进行操作。突然间,我决定让事情变得更复杂一些,然后麻烦就开始了。我的代码应该添加一个按钮,如果该按钮在站点中不存在,则该按钮将突出显示找到的正则表达式匹配项,但它不起作用,您可以测试最好自己购买。这里是:

var rExpIni = /^\b(?:[A-Z][^aeiou\d\s][a-z]{2})\b\s\b(?:[A-Z][a-z]{2}|[a-z]{3})\b/gm;
var rExp = /\b(?:[A-Z][^aeiou\d\s][a-z]{2})\b\s\b(?:[A-Z][a-z]{2}|[a-z]{3})\b/gm;

function sim(){
    $("p, a, span, em, i, strong, b, h1, h2, h3, td, th, hr").each(function(){
        if( rExpIni.test($(this).text()) == true){
            $(this).css({
                "background-color":"#DDBB22",
                "border-style":"outset",
                "border-width":"3px",
                "border-color":"#DDBB22",
                "font-size":"12pt",
                "font-weight":"bold",
                "color":"red"
            });
        }
    });
    $("img").each(function(){
        if( rExp.test($(this).attr("title")) == true || rExp.test($(this).attr("alt")) == true ){
            $(this).css({
                "border-style":"inset",
                "border-width":"10px",
                "border-color":"#DDBB22",
                "font-size":"12pt",
                "font-weight":"bold",
                "color":"red"
            });
        }
    });
}

function nao() {
    $("p, a, span, em, i, strong, b, h1, h2, h3, td, th, hr, img").each(function(){
        $(this).css({
            "background-color":"",
            "border-style":"",
            "border-width":"",
            "border-color":"",
            "font-size":"",
            "font-weight":"",
            "color":""
        });
    });
}
$(document).ready(function(){
    if($("body:not(body:has(button#but))")){
        var nBotao = $("<button id=\"but\">Procurar</button>");
        $("body").prepend(nBotao);
    }
});
$("#but").toggle(sim(),nao());
4

1 回答 1

3

您可以使用 jQuery 对象的length属性:

if ($('#but').length == 0) {
    var nBotao = $("<button id='but'>Procurar</button>");
    $("body").prepend(nBotao);
}

此外,当您动态生成元素时,您应该委托事件:

var which = true;
$(document).on('click', '#but', function() {
     if (which) {
         sim()
         which = false;
     } else {
         nao()
         which = true;
     }
})

请注意,toggle()方法是deprecated,您应该将所有代码放在$(document).ready();

于 2012-08-05T05:13:41.740 回答