我对jQuery中的条件有点困惑。我想将'if'条件放入jQuery函数中。这是对的吗?还是比这更好的任何其他解决方案?
我希望将此方法放入jQuery函数下面 - 我该如何实现它?
if($(this).attr("id")=='emptys'){
data = { msg : datas } //this is element inside of ajax
}
else{
data = { pid : datas } //this is element inside of ajax
}
我想把这个方法放在下面的函数
中<script>
$(document).ready(function(){
$('.but').click(function(){
var datas = $(this).attr("id");
$.ajax({
type: 'GET',
url:"addcart.php",
data : { pid : datas },
success:function(result){
$("#div1").html(result);
}});
});
});
</script>
答案 0 :(得分:3)
尝试
$(document).ready(function () {
$('.but').click(function () {
var data;
if (this.id == 'empty') {
data = {
msg: datas
}
} else {
data = {
pid: datas
}
}
$.ajax({
type: 'GET',
url: "addcart.php",
data: data,
success: function (result) {
$("#div1").html(result);
}
});
});
});
或更好
$(document).ready(function () {
$('.but').click(function () {
var data = {};
data[this.id == 'empty' ? 'msg' : 'pid'] = this.id
$.ajax({
type: 'GET',
url: "addcart.php",
data: data,
success: function (result) {
$("#div1").html(result);
}
});
});
});
答案 1 :(得分:1)
<script>
$(document).ready(function(){
$('.but').click(function(){
var datas = $(this).attr("id");
var tempdata;
if(datas ==''){// if empty then check by ""
tempdata= { msg : datas } //this is element inside of ajax
}
else{
tempdata= { pid : datas } //this is element inside of ajax
}
$.ajax({
type: 'GET',
url:"addcart.php",
data : tempdata,
success:function(result){
$("#div1").html(result);
}});
});
});
</script>
答案 2 :(得分:0)
<script>
$(document).ready(function(){
$('.but').click(function(){
var datas = $(this).attr("id");
if(datas =='empty'){
data : { msg : datas } //this is element inside of ajax
}
else{
data : { pid : datas } //this is element inside of ajax
}
$.ajax({
type: 'GET',
url:"addcart.php",
data : data,
success:function(result){
$("#div1").html(result);
}});
});
});
</script>