2017-06-21 62 views
-1

我有一个函数,我想用于两个非常类似的操作(如和不同)。我相信我需要重新命名一些东西,但在网上搜索后,我找不到如此明显的东西。任何帮助,非常感谢。如何在javascript中重命名函数

剧本我想重新命名:

<script> 
$(function() { 
// get into the habit of caching the elements you will be re-using 
var error = $('.error'); 

$('.button').click(function() { 
    error.hide(); 

    // cache all the elements we'll be using 
    var contactForm1 = $(this).closest('.contact_form1'), 
     likesid = contactForm1.find('input[name=likesid]'), 
     likerid = contactForm1.find('input[name=likerid]'); 
     unlikestatus = contactForm1.find('button1[name=unlikestatus]'); 

    if (likesid.val() == '') { 
     // ... 
     likesid.focus(); 
     return false; 
    } 
    if (likerid.val() == '') { 
     // ... 
     likesid.focus(); 
     return false; 
    } 

    // easier to use object rather than string 
    // not sure where likestatus came from so it is ommitted 
    var data = { likesid: likesid.val(), unlikestatus: unlikestatus.val(), likerid: likerid.val() }; 

    // short-hand method for $.ajax with POST 
    $.post('simpletest.php', data, function (res) { 
     // the rest 
     contactForm.html('<h5 class="message" style="color: #4EB44B;">unliked</h5>') 
    }); 

    // no need to do any return false 
}); 
}); 
</script> 
+0

要重命名的函数或脚本? – mkaatman

+0

我不确定,我对JavaScript很陌生。我正在寻找任何可以让我使用相同代码两次的方法,只需更改一些东西 – sicksixstrings

+2

将它们作为参数传递给您的函数 –

回答

1

你的问题还不清楚,但假设你只需要通过按钮属性,以确定哪个按钮被点击,就可以通过按钮本身做到这一点。

JavaScript函数:

$(function() { 
    $(".buttonClassName").click(function() { 
    //Method 1 to retrieve custom data from the button 
    alert($(this).attr("data-somedata")); 
    //Method 2 to retrieve custom data from the button (newer jQuery >= 1.4.3) 
    alert($(this).data("somedata")); 
    }); 
}); 

HTML:

<button class="buttonClassName" data-somedata="someTestDataFromButton1">Like</button> 
<button class="buttonClassName" data-somedata="someTestDataFromButton2">Dislike</button> 

小提琴:https://jsfiddle.net/qpLoh3tz/1/

+0

是否有可能改变--- $('。button')。click(function(){--- so that instead of“.button “,我可以参考一个类或按钮的编号? – sicksixstrings

+0

在这种情况下,”。按钮“是按钮的类名称,你可以有任何你想要的名字 –

+0

我已经更新上面的类名称和如果你想使用id,然后将逻辑封装在一个函数中,并在任何一个按钮被点击时调用该函数。 –

相关问题