2

3 つの要素があり、それぞれに ID がある Web ページを作成しています。スクリプト セクションには、html ID と同じ名前の 3 つの関数があります。要素をクリックすると、それぞれの関数を実行したいです。コード:(フィドル)

HTML:

<div id="one" class="btn">
  Click here for 1
</div>
<div id="two" class="btn">
  Click Here for 2
</div>
<div id="three" class="btn">
  Click Here for 3
</div>

JQ:

$('.btn').on('click',function(){
  $(this).attr('id')()  //here I want to run function
});
function one(){alert("one clicked")}
function two(){alert("two clicked")}
function three(){alert("three clicked")}

助けてください..if文を使いたくない...私はこれを最も最適化された方法でやろうとしています..:)フィドルのリンクは次のとおりです

4

5 に答える 5

10

以下のように関数をオブジェクトとして定義し、

var myFunc = {
  one: function (){alert("one clicked")},
  two: function (){alert("two clicked")},
  three: function (){alert("three clicked")}
};

ハンドラー内で次のように呼び出します。

myFunc[this.id](); //Note: this.id is good and better than $(this).attr('id')
于 2013-06-27T16:30:17.993 に答える
3

window グローバル オブジェクトを使用する別の方法:

デモ

$('.btn').on('click',function(){
      window[this.id]();  //here I want to run function            
});
one = function(){alert("one clicked")}
two = function(){alert("two clicked")}
three = function(){alert("three clicked")}
于 2013-06-27T16:34:46.580 に答える
1

わかりました、これを試してください:

var theFunctions = {
      one: function () { alert("one clicked"); },
      two: function () { alert("two clicked"); },
      three: function () { alert("three clicked"); },
};

$('.btn').on('click',function(){
   theFunctions[$(this).attr('id')](); //here I want to run function
});

あなたはそれをチェックアウトすることができます: http://jsfiddle.net/RFane/

于 2013-06-27T16:34:35.673 に答える
0
$('.btn').on('click',function(){
    eval($(this).attr('id'))();
});
于 2013-06-27T16:32:38.710 に答える
0

使用できますeval

eval($(this).attr('id'));

注: このメソッドを使用する前に、 evalについて読む必要があります。

于 2013-06-27T16:30:32.200 に答える