English 中文(简体)
Extracting numbers from the parent attribute in jQuery
原标题:

By clicking on the "mylink" I want the link to be replaced by the number "123", which is extracted from parent tag. I think I m not doing the ".match(...." right.

jQuery:

$(document).ready(function(){
  $(".link").click(function(){
    var comid = $(this).parents("div.comment").attr("class").match(/comment-([0-9]+)/)[1];
    $(".link").replaceWith(comid);
  });
});

html:

<div class="comment comment-123 ct">
  <div class="link">mylink</div>
</div>
最佳回答

You only have one matching so you need to use the 0th match (zero-based array). Also, it will return the entire match, so if you want just the number you ll need to remove the comment- text from it.

$(document).ready(function(){
  $(".link").click(function(){
    var comid = $(this).parents("div.comment")
                       .attr("class")
                       .match(/comment-[0-9]+/)[0]
                       .replace( comment- ,  );
    $(".link").replaceWith(comid);
  });
});

If there s a possibility that no match will occur, then you d want to assign the matches to a variable and only do the replacement(s) if a match occurs (the variable is non-null).

问题回答

暂无回答




相关问题
getGridParam is not a function

The HTML: <a href="javascript:void(0)" id="m1">Get Selected id s</a> The Function: jQuery("#m1").click( function() { var s; s = jQuery("#list4").getGridParam( selarrrow )...

selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

jQuery cycle page with links

I am using the cycle plugin with pager functionality like this : $j( #homebox ) .cycle({ fx: fade , speed: fast , timeout: 9000, pager: #home-thumbs , ...

jquery ui dialog opens only once

I have a button that opens a dialog when clicked. The dialog displays a div that was hidden After I close the dialog by clicking the X icon, the dialog can t be opened again.

jConfirm with this existing code

I need help to use jConfirm with this existing code (php & Jquery & jAlert). function logout() { if (confirm("Do you really want to logout?")) window.location.href = "logout.php"; } ...

Wrap text after particular symbol with jQuery

What I m trying to do, is wrap text into div inside ll tag. It wouldn t be a problem, but I need to wrap text that appears particularly after "-" (minus) including "minus" itself. This is my html: &...

热门标签