2017-07-09 3 views
0

2つの引数を持つ関数のパラメータ値を取得する正しい構文は何ですか?html文字列チェーンからパラメータ値を取得するための正しい構文

最初に私のremoveRow(id)関数は、処理するために1つのパラメータしか必要としません。

htmlコード:

"<a href=javascript:removeRow("+sport.id+"); class='btn btn-xs btn-warning'>remove</a>" 

jsのコードは: //削除行今

function removeRow(sportId) { 
    if ('undefined' != typeof sportId) { 
     console.log(sportId); 
    } else alert('Unknown id.'); 
} 

、私は、この関数は二つのパラメータ(構文???を取りたいです)

htmlコード:

"<a href=javascript:removeRow("+sport.id+","+ event.id+"); class='btn btn-xs btn-warning'>remove</a>" 

JSコード:

// Remove row 
function removeRow(sportId,eventId) { 
    if ('undefined' != typeof sportId) { 
     console.log(sportId+ " " + eventId); 
    } else alert('Unknown id.'); 
} 
+1

hrefが内側に引用符ではありません。 – Shubham

+1

しないでください。クリックハンドラを使用します。 –

答えて

1

あなたがIDを引用し、このような引用符をエスケープする必要があります。

"<a href='javascript:removeRow(\""+sport.id+"\",\""+event.id+"\")' class='btn btn-xs btn-warning'>remove</a>" 

が、私は強くあなたがお勧めしますJavaScriptのhrefを使用せず、代わりにデータ属性を使用すること

'<a href="#" onclick="return removeRow(this)" data-sportid="'+sport.id+'" data-eventid="'+event.id+'" class="btn btn-xs btn-warning">remove</a>' 

とクラスを追加控えめ

window.onload=function() { 
    var sportLinks = document.querySelectoraAll(".sport"); 
    for (var i=0;i<sportLinks.length;i++) { 
    sportLinks[i].onclick=function removeRow(e) { 
     e.preventdefault(); // cancel link event 
     var sportId = link.getAttribute("data-sportid"), 
      eventId = link.getAttribute("data-eventid"); 
     if ('undefined' != typeof sportId) { 
     console.log(sportId+ " " + eventId); 
     } 
     else alert('Unknown id.'); 
    } 
    } 
} 

を同じことを行うには

function removeRow(link) { 
    var sportId = link.getAttribute("data-sportid"), 
     eventId = link.getAttribute("data-eventid"); 
    if ('undefined' != typeof sportId) { 
    console.log(sportId+ " " + eventId); 
    } 
    else alert('Unknown id.'); 
    return false; // cancel the link 
} 

を使用します。

'<a href="#" data-sportid="'+sport.id+'" data-eventid="'+event.id+'" class="sport btn btn-xs btn-warning">remove</a>' 
関連する問題