Jquery在按钮不存在时添加按钮
为了试验,我在百思买(bestbuy.com)的控制台上闲逛,尝试一些正则表达式。突然,我决定让事情变得更复杂一点,然后麻烦开始了。我的代码应该添加一个按钮,该按钮将突出显示找到的有关正则表达式的匹配项,如果该按钮在站点中不存在,但不起作用,您可以自己测试。这是:Jquery在按钮不存在时添加按钮,jquery,events,css-selectors,jquery-selectors,Jquery,Events,Css Selectors,Jquery Selectors,为了试验,我在百思买(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
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());
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}{124;[A-Z]{3})\b/gm;
函数sim(){
$(“p、a、span、em、i、strong、b、h1、h2、h3、td、th、hr”)。每个(函数(){
if(rExpIni.test($(this.text())==true){
$(this.css)({
“背景色”:“DDBB22”,
“边界样式”:“开始”,
“边框宽度”:“3px”,
“边框颜色”:“DDBB22”,
“字体大小”:“12pt”,
“字体大小”:“粗体”,
“颜色”:“红色”
});
}
});
$(“img”)。每个(函数(){
if(rExp.test($(this.attr(“title”))==true | | rExp.test($(this.attr(“alt”))==true){
$(this.css)({
“边框样式”:“插图”,
“边框宽度”:“10px”,
“边框颜色”:“DDBB22”,
“字体大小”:“12pt”,
“字体大小”:“粗体”,
“颜色”:“红色”
});
}
});
}
函数nao(){
$(“p、a、span、em、i、strong、b、h1、h2、h3、td、th、hr、img”)。每个(函数(){
$(this.css)({
“背景色”:“,
“边框样式”:“,
“边框宽度”:“,
“边框颜色”:“,
“字体大小”:“,
“字体大小”:“,
“颜色”:”
});
});
}
$(文档).ready(函数(){
if($(($)body:not(body:has(button#but))){
var nBotao=$(“ProCur”);
$(“正文”)。前置(nBotao);
}
});
$(“#但是”).toggle(sim(),nao());
您可以使用jQuery对象的length
属性:
if ($('#but').length == 0) {
var nBotao = $("<button id='but'>Procurar</button>");
$("body").prepend(nBotao);
}
请注意,toggle()
方法是,您应该将所有代码放在$(文档)中。ready()
var which = true;
$(document).on('click', '#but', function() {
if (which) {
sim()
which = false;
} else {
nao()
which = true;
}
})