简体   繁体   中英

Right syntax to get parameters values from html string chain

what is the correct syntax in this case to get parameters values for a function with two arguments.

At first my removeRow(id) function need only one parameter to do process.

html code:

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

js code: // Remove row

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

Now, i want this function to take two parameters( syntax??? )

html code:

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

js code:

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

You need to quote the IDs and escape the quotes like this:

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

but I strongly recommend you do NOT use a javascript href and also that you use data attributes instead

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

and use

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
}

To do the same unobtrusively

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.'); 
    }
  }
}

adding a class:

'<a href="#" data-sportid="'+sport.id+'" data-eventid="'+event.id+'" class="sport btn btn-xs btn-warning">remove</a>' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM