1

我瘋了,嘗試一些正則表達式爲了試驗,我在bestbuy.com控制檯上做。突然之間,我決定讓事情更復雜一些,然後麻煩就開始了。我的代碼應該添加一個按鈕,該按鈕將突出顯示所查找的正則表達式的匹配項,如果該按鈕在站點中不存在,但它不起作用,那麼您可以測試是否最好是自己購買。那就是:jquery添加一個按鈕,如果它不存在

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()); 

回答

2

可以使用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();

+1

Upvote指出濫用toggle() – 2012-08-05 05:23:12

相關問題