2017-06-21 9 views
-1

私は2つの非常によく似たアクション(likeとlikeと)に使いたい機能を持っています。私は何かの名前を変更する必要があると確信していますが、オンラインで検索したところ、一見明らかなものは見つけられませんでした。どんな助けでも大変感謝しています。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に新しいです。私は何かをいくつか変更するだけでこの同じコードを2回使うことができるものを探しています – 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 .buttonを参照する代わりに"ボタンのクラスまたはIDを参照できますか? – sicksixstrings

+0

このコンテキストでは、" .button "はボタンのクラス名です。任意の名前を付けることができます。 –

+0

上記のクラス名を更新しました。あなたがIDを使用したい場合は、関数内でロジックをラップし、ボタンのいずれかがクリックされたときに関数を呼び出すこと。 –

関連する問題