関数参照は、オブジェクトの単なるプロパティです。JavaScript では、次の2 つの方法でオブジェクト プロパティにアクセスできます。
ドット表記とリテラル プロパティ名の使用:obj.foo
括弧付き表記と文字列プロパティ名を使用:obj["foo"]
後者の場合、文字列は任意の式の結果である可能性があります。
プロパティにアクセスしたら、追加()
して呼び出すだけです。
そう:
evtsheet['it3L']();
また
evtsheet.it3L();
これらのいずれかを使用すると、呼び出し内this
でevtsheet
.
あなたが言った
この値にアクセスして、変数に格納することができました。
次のようにできます。
var f = evtsheet['it3L'];
また
var f = evtsheet.it3L;
そしてそれを呼び出します:
f();
ただし、それを行うと、通話に参加できないことthis
に注意してください。(厳密モードかどうかに応じて、グローバル オブジェクトまたはになります。)evtsheet
undefined
もっと:
HTML から名前を再取得します。つかみやすいように、次のように変更します(あなたが持っている方法では難しくありませんが、このように簡単です):
<div id="it3" evt="swipeleft|swiperight" act="evtsheet.it2L|evtsheet.it3R" class="focusable off" style="width: 25%; height: 26.031746031746035%; top: 60.63492063492063%; left: 44.82142857142858%; z-index: 998; "></div>
<div id="it4" evt="swipeleft|swiperight" act="evtsheet.it3L|evtsheet.it4R" class="focusable off" style="width: 25%; height: 25.709325396825395%; top: 60.952380952380956%; left: 60.357142857142854%; z-index: 999; ></div>
したがって、使用split
してその一部を取得できます。
com.xxx.init = function(ele) { //ele = "#it3"
var e = $(ele).attr("act").split("|");
// This assumes `evtsheet` is a global variable
// Here's how to call the function defined by `e[0]`:
var parts = e[0].split('.');
window[parts[0]][parts[1]]();
// (And you can generalize it for any of the other functions in
// the `e` array)
}
それはグローバル変数であると想定しevtsheet
ています(それはあなたの質問にあります)。私はグローバル変数が好きではないので、おそらくすべてのコードをスコープ関数に入れて (グローバルの作成を避けるため)、次のようにします。
<script>
// Start the scoping function
(function() {
// Make evtsheet a property of an object
var stuff = {
evtsheet: {
it2L : function(){/*some code*/},
it3L : function(){/*some code*/},
it3R : function(){/*some code*/},
it4L : function(){/*some code*/},
/*have more similar functions*/
}
};
// ...other stuff...
com.xxx.init = function(ele) { //ele = "#it3"
var e = $(ele).attr("act").split("|");
// We no longer assume `evtsheet` is a global, but it *is*
// a property on `stuff`.
// Here's how to call the function defined by `e[0]`:
var parts = e[0].split('.');
stuff[parts[0]][parts[1]]();
// (And you can generalize it for any of the other functions in
// the `e` array)
};
// ...other stuff...
// End of scoping function
})();
</script>
名前をそのままにしておきたい場合は、代わりにかなり単純な正規表現を使用します。
var parts = /^([^[]+)['([^']+)']$/.exec(e[0]);
if (parts) {
stuff[parts[1]][parts[2]](); // Note the indexes changed
}