2013-10-16 37 views
1

我對jQuery中的條件有點困惑。我想把'if'條件放入一個jQuery函數中。這是對的嗎?還是比這更好的解決方案?如果條件變成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

所以你有沒有試過它,是否有任何錯誤。? –

+0

'empty'是一個'ID'還是你正在檢查'id ='''或者什麼? –

+0

空(只是一個字)只是傳遞值id – kalyan

回答

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); 
      } 
     }); 
    }); 
}); 
+0

其工作正常...謝謝阿倫.. – kalyan

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> 
+0

爲什麼downvote downvoter –

+0

因爲你的代碼有錯誤。它不會工作。這不是你給變量賦值的方式。 – ahren

+0

感謝@ahren的重點我已更新我的代碼 –

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> 
+0

這也工作...謝謝 – kalyan