Passing a parameter from an html element using jQuery

I am working with jQuery for the first time and need some help. I have an html that looks like this:

<div id='comment-8' class='comment'>
    <p>Blah blah</p>
    <div class='tools'></div>
</div>

<div id='comment-9' class='comment'>
    <p>Blah blah something else</p>
    <div class='tools'></div>
</div>

I am trying to use jQuery to add spacing to div.tools that call variouis functions when clicked. Functions must get the identifier (either the entire comment-8 or part "8") of the parent comment so that I can then show the form or other information about the comment.

What I have so far:

<script type='text/javascript'>

    $(function() {
        var actionSpan = $('<span>[Do Something]</span>');
        actionSpan.bind('click', doSomething);

        $('.tools').append(actionSpan);
     });

     function doSomething(commentId) { alert(commentId); }

</script>

I am fixated on how to populate the commentId parameter for doSomething. Perhaps, instead of id, I should pass a link to the passed interval. It may be fine, but I'm not sure how to do it.

Thanks Brian

+3
source share
6

, - . target, , , this , . , :

function doSomething(event)
{
    var id = $(event.target).parents(".tools").attr("id");
    id = substring(id.indexOf("-")+1);
    alert(id);
}

... :

function doSomething(event)
{
    var id = $(this).parents(".tools").attr("id");
    id = substring(id.indexOf("-")+1);
    alert(id);
}
+6

div, <tt>parent()</tt> ( ), : <tt>$(this).parent().attr('id')</tt>; , (), DOM, : <tt>$(this).parents('div:eq(0)').attr('id')</tt>.

, <tt>"comment"</tt>, , , , div.

+1

, .

, - doSomething():

function doSomething() { 
  var commentId = $(this).parent().attr('id');
  alert(commentId); 
}
0

, . , . , , , , , .

( , ), , .

<script type='text/javascript'>

$(function() {
  $('.comment').each(function(comment) {
    $('.tools', comment).append(
      $('<span>[Do Something]</span>')
          .click(commentTool(comment.id));
    );
  });
});

function commentTool(commentId) {
  return function() {
    alert('Do cool stuff to ' + commentId);
  }
}

</script>
0

, , :

var tool = $('<span>[Tool]</span>');

var action = function (id) {
    return function () {
        alert('id');
    }
}

$('div.comment').each(function () {
    var id = $(this).attr('id');

    var child = tool.clone();
    child.click(action(id));

    $('.tools', this).append(child);
});
0

The bind () function accepts, accepts the element as a parameter (in your case, span), so to get the identifier you want from it, you must do a DOM traversal, for example:

function doSomething(eventObject) { 
    var elComment = eventObject.parentNode.parentNode; //or something like that, 
                                                       //didn't test it
    var commentId= elComment.getAttribute('commentId')
    alert(commentId); 
}
0
source

Source: https://habr.com/ru/post/1697482/


All Articles