如何在javascript中重命名函数

时间:2017-06-21 04:34:40

标签: 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>

1 个答案:

答案 0 :(得分: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/