我为了试验而四处闲逛并尝试一些正则表达式,我在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());
答案 0 :(得分: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()
;