Javascript - 动态更改参数功能on

时间:2016-06-10 15:45:39

标签: javascript function parameters onclick

我前面有这样的事情:

<a href="javascript:;" onclick="save_todo(10, 12, 0);" >Save todo</a>

我在JavaScript中的功能如下:

function save_todo(id_user, id_todo, id_check){

dataString = "q1="+id_user+"&q2="+id_todo;


  if(id_check == 0){
    // Add to favorite
    jQuery.ajax({
        type: "POST",
        url: "todo_submit.php",
        dataType: 'html',
        data : dataString,
        cache: false,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("erreur add");
        },
        success: function (html) {
            console.log("sucess add");
        }  
    });
  } else {
// Remove to favorite
    jQuery.ajax({
        type: "POST",
        url: "todo_submit_delete.php",
        dataType: 'html',
        data : dataString,
        cache: false,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("erreur remove");
        },
        success: function (html) {
            console.log("sucess remove");
        } // success  
    }); // ajax
  }
  console.log("function call");
}

是否可以更改函数save_todo onClick的参数,它是否有效? 我只想将最后一个参数更改为1(如果它为0),反之亦然。

Thanx!

1 个答案:

答案 0 :(得分:0)

如果要传递1,只需将值更改为1即可: &#39;保存待办事项&#39;

但我明白,你想根据某些条件改变这个值。为此,您可以先设置此参数的值,然后使用该参数调用:

<a href="#" id="save-to-do">Save todo</a>

$("#save-to-do").on("click", function(e){
  e.preventDefault();
  var paramValue = 0;

  //  if( some condition )
      // paramValue = 1;

  save_todo(10, 12, paramValue);
});//click

根据您使用的代码,这里是更正后的代码:

$("#identification_sct a.btn").on('click', function(e){
    var id_check = $(this).attr("data-id-check"); 

    save_todo(10, 12, id_check);

    if(id_check == 0)
        { id_check = 1; }
    else{ id_check = 0; }
    $(this).attr("data-id-check", id_check);
}

您的代码中存在一些不正确的逻辑。