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(...." 开发者_Python百科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).
精彩评论