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 に答える