简体   繁体   中英

Jquery how to add onclick in href

how to add onclick='openLightB('remove_ddi',500);' in to <a>open</a> with jquery function

my present code is like this

$(".remove_row").live("click", function(){
  $(".ddi tr:eq(2) td:eq(5) a").replaceWith("<a onclick='openLightB('remove_ddi',500);'>Remove</a>");
});

unfortunately result coming like this

<a remove_ddi',500);'="" onclick="openLightB(">Remove</a>

How about letting jquery deal with escaping the quotes by using .attr() :

$(".remove_row").live("click", function(){
  $(".ddi tr:eq(2) td:eq(5) a").attr('onclick', "openLightB('remove_ddi',500);");
});

DEMO


BTW, .live() is deprecated and could be removed from the library any time in the future. You should consider using .delegate() or .on() for event delegation.

You can fix your code by changing it as below,

$(".remove_row").live("click", function(){
  $(".ddi tr:eq(2) td:eq(5) a")
     .replaceWith("<a onclick=\'openLightB(\'remove_ddi\',500);\'>Remove</a>");
});

or simplify it,

 $(".remove_row").live("click", function(){
    $(".ddi tr:eq(2) td:eq(5) a").click (function () {
      $(this).text('Remove');
      openLightB('remove_ddi',500);
     });
 });

Also if you are using jQuery 1.7, then use .on

//replace <.remove_row container> with .remove_row container
 $('<.remove_row container>').on("click", '.remove_row', function(){
    $(".ddi tr:eq(2) td:eq(5) a").click (function () {
      $(this).text('Remove');
      openLightB('remove_ddi',500);
     });
 });

This work for quotes problems:

$(document).ready(function(){
    $(".remove_row").click( function(){
          $(".ddi tr:eq(2) td:eq(5) a").replaceWith("<a onclick=\"openLightB('remove_ddi',500);\">Remove</a>");
        });
});
$(".remove_row").live("click", function(){
  $(".ddi tr:eq(2) td:eq(5) a").attr('onclick', 'openLightB("remove_ddi",500);');
});

try this

<a href="javascript:openLightB('remove_ddi',500)">Remove</a>

jquery

$(".remove_row").live("click", function(){
  $(".ddi tr:eq(2) td:eq(5) a").prop('href','javascript:openLightB("remove_ddi",500);');
});
$(".remove_row").live("click", function(){
 $(".ddi tr:eq(2) td:eq(5) a").attr('onClick', 'openLightB("remove_ddi",500);'); });

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