我有2个直播事件需要更改背景颜色,无论用户是否单击.padd或.paddc上的按钮。第一个按钮正在工作,背景可以改变而不是第二个按钮。使用jQuery的代码有什么问题?
<a id="hms" href="1" onClick="adduser('1'); return false;"><img id="t1" class="padd" src="tta/addr.png"></a>
<a id="hms2" href="2" onClick="validateuser('2'); return false;"><img id="te2" class="paddc" src="tta/addr.png"></a>
$(document).ready(function(){
var ffd = "0";
$(".padd").live('click',function(event){
//update profile - remove pending
$.ajax({
type: "POST",
cache: "false",
url: "pendingupd.php?pid="+event.target.id,
success: function(aaa) {
var ttf= "#t" + event.target.id;
if(aaa=="Approved"){
$(ttf).css("background","url('tta/pass.png') 50% 50px no-repeat");
$(ttf).css("background-color","#ffffda");
} else {
$(ttf).css("background","none");
$(ttf).css("background-color","none");
}
if(aaa=="Error"){
$(ttf).css("background-color","#f0b7b7");
}
}
});
});
$(".paddc").live('click',function(event2){
//update profile - remove pending
$.ajax({
type: "POST",
cache: "false",
url: "pendingupd.php?pid="+event2.target.id,
success: function(aaa2) {
var ttf2= "#te" + event2.target.id;
if(aaa2=="Approved"){
$(ttf2).css("background","url('tta/pass.png') 50% 50px no-repeat");
$(ttf2).css("background-color","#ffffda");
} else {
$(ttf2).css("background","none");
$(ttf2).css("background-color","none");
}
if(aaa2=="Error"){
$(ttf2).css("background-color","#f0b7b7");
}
}
});
});
});
答案 0 :(得分:0)
这两个函数之间的唯一区别是第一个函数有var ttf= "#t" + event.target.id;
而第二个函数有var ttf2= "#te" + event2.target.id;
这让我相信问题可能在DOM中。你确定一切都有正确的ID吗?那些真的应该是不同的吗?
无论哪种方式,该代码的较短版本可能如下所示:
$(document).ready(function(){
var ffd = "0";
// jQuery lets you select more than one element.
// combining them makes what you intend more obvious.
// and it means you create fewer functions.
$(".padd, .paddc").live('click',function(event){
var ttf= $(this).hasClass( ".paddc" )? "#t": "#te" ;
//update profile - remove pending
$.ajax({
type: "POST",
cache: "false",
url: "pendingupd.php?pid="+event.target.id,
success: function(aaa) {
// replace this with ttf = "#t" if te was a typo.
updatePendingState( aaa, ttf + event.target.id );
}
});
});
});
// there is no point in having this as something created
// EVERY time that an AJAX call is made (the old way).
function updatePendingState( aaa, selector )
{
// initialize values to defaults.
var bgColor = "none", bgImg = "none";
if(aaa=="Approved"){
// update if a change is merited.
bgColor = "url('tta/pass.png') 50% 50px no-repeat";
bgImg = "background-color","#ffffda";
} else if(aaa=="Error"){
bgColor = "#f0b7b7";
}
// grab the value once and use it multiple times. Why wast function calls?
var ttf = $(selector);
ttf.css("background",bgImg);
ttf.css("background-color",bgColor);
}