Pregunta

I am working on a voting functionality in forum. I am looping through answers of a post, and every answer has a unique ID. Every "answer" has some text, dates and other data.

I have also added an image the users clicks to vote, with a class:

<asp:Image runat="server" ImageUrl="~/Resources/Images/UpVoteImg.png" CssClass="upvote"/>

In my script I catch all click events with the class upvote :

<script>
    $('.upvote').click(function () {
        var url = '<%= ResolveUrl("~/services/forumservice.asmx/voteup") %>';
        var userId = <%=SystemContext.Instance.SystemUser.UserId %>;

        var data = '{"entry":"' + 'HOW_DO_I_GET_YOU?' + '", "userid":"' + userId + '"}';
        $.ajax({
            type: "POST",
            url: url,
            contentType: "application/json; charset=utf-8",
            data: data,
            success: function () {
                alert('Thanks');
            },
            error: function () {

            }
        });
    });
</script>

My problem: When clicking on this image, I want to call a webservice with the ID of the answer.

What have I tried / thought of:

  • I am sure the this keyword is a way to go here, if some data-attribute was added to the image. I couldn't find an example though (probably wrong search words)
  • Making an onclick() on the image, which sets a private field, I then read in my click event (yes, I want to avoid that)
¿Fue útil?

Solución

You will want to use a combination of the closest and attr methods in jQuery.

For example:

var userId = $(this).closest(.answercontainer).attr('id');

$(this) is a jquery object for the element that was clicked on

.closest(selector) traverses up the DOM tree until it reaches a match for the selector

.attr('id') gives you the value in the id attribute of the traversed to element

If the ID is elsewhere in your DOM you may need to look at some other traversing methods such as siblings or find.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top