2017-08-18 13 views
4

コードを減らしたい。同じidパターンを持つボタンのonclick機能を1つ - JavaScript

function one() { 
console.log("hai"); 
} 

document.getElementById('dealsButton_1').onclick = one; 
document.getElementById('dealsButton_2').onclick = one; 
//I want the above 2 lines of code reduced to one. 

「dealsButton_ *」をクリックすると、id要素がパターン化されます。これどうやってするの。 要素は動的にロードされます

+1

「one」と「two」が同じことをする場合、なぜ機能する必要がありますか? – PeterMader

+0

申し訳ありません私の編集を待ちます。 – Dexter

+0

静的な親要素へのイベント委譲の使用、対象要素のidプロパティの確認、一致する場合は適切な関数の呼び出し –

答えて

4

あなたは、単一の行でイベントリスナーを追加するquerySelectorAllセレクタ[id^=dealsButton_]を使用することができます - デモ下記参照:

function one() { 
 
console.log("hai"); 
 
} 
 

 
Array.prototype.forEach.call(
 
    document.querySelectorAll('[id^=dealsButton_]'), function(e) { 
 
    e.addEventListener('click', one); 
 
});
<div id="dealsButton_1">one</div> 
 
<div id="dealsButton_2">two</div>

をマークアップが動的にロードされている場合あなたはベースそれはでこのようなIC要素:

function one() { 
 
    console.log("hai"); 
 
} 
 

 
document.addEventListener('click', function(e) { 
 
    if (e.target && /^dealsButton_/.test(e.target.id)) 
 
    one(); 
 
}) 
 

 
// dynamically add 
 
document.body.innerHTML = `<div id="dealsButton_1">one</div> 
 
<div id="dealsButton_2">two</div>`;

+1

あなたの答えはまだ最も重要なニュアンスを逃していると思う:* "要素が動的に読み込まれている"* – dfsq

+0

@dfsq編集された答え、頭のおかげで:) – kukkuz

+1

正規表現なし:' if(e.target && e.target.matches( '[id^= dealsButton_]'){...} ' – PeterMader

0

あなたはこのような何かを探しています:ここで

function onClick(){ 
    //single handler 
} 

$('[id*="dealsbutton_"]').click(onClick) 
0

uは特定せずに望むようにあなたがID名を選択することができますソリューションです名前のパターン。動的関数呼び出しの名前を作りたい場合は、この

$.each($("button[id^='dealsButton_']"), function() { 
$(this).on('click', function(){ 
    //code here 
}) 
}); 

のために正規表現でのjQueryを使用

<html> 
    <body> 
    <div id="abc">one</div> 
    <div id="def">two</div> 

    <script type="text/javascript"> 
     function one() { 
     console.log("hai"); 
     } 

     function addOnclickFunc (func, idArray){ 
     idArray.forEach(function(element) { 
      document.getElementById(element).onclick = func; 
     }) 
     } 

     addOnclickFunc(one,["abc","def"]) 
    </script> 
    </body> 
</html> 
-1

。ボタンの要素にデータ属性として渡し、eval関数を使って呼び出します。

<button id="dealButton_1" data-click="one"></button> 

$.each($("button[id^='dealsButton_']"), function() { 
$(this).on('click', function(){ 
    var function_call = $(this).attr('data-click') 
    eval(function_call) 
}) 
}); 
関連する問題