简体   繁体   中英

In jQuery how do I get an id from an attribute if I can't use 'this'?

Thank you for taking a look at my question which goes as follows:

I'm using a jQuery plugin called Inline inline affirm which basically just asks the user for a confirmation (yes or no) on the action they're performing.

this is the basic usage of the plugin:

HTML:

<li class="msg-li-delete" data-msgid="<?php echo $msg_id_att; ?>">
          <div class="affirm light"
               data-id="<?php echo $msg_id_att; ?>"
               data-title="delete"
               data-question="are you sure?" style="display:inline-block;"></div></li>

JS:

$(".affirm").inlineAffirm({
    callback : function(ele){
        var msg_id_conf = $(".affirm").attr("data-id");
        delete_private_msg(msg_id_conf);
      }
  });

The problem with this is that I'm trying to get a unique id from the anchor tag so I can call the delete_private_msg function and give the id as an argument, the delete_private_msg function will do some ajax interactions with PHP to delete the message.

It doesn't matter on which anchor I click the item that's deleted is always the first one.

So I tried this:

  $(".affirm").inlineAffirm({
      var thisid = $(this).attr("data-id");
        callback : function(ele){
            var msg_id_conf = thisid;
            delete_private_msg(msg_id_conf);
          }
      });

But I get the following error in console:

126 Uncaught SyntaxError: Unexpected identifier

Any help on this would be greatly appreciated, I really hope it's understandable.

Not sure if its working, but if the callback is called in the onclick handler, then this should work

$(".affirm").inlineAffirm({
    callback : (ele) => {
        var msg_id_conf = $(this).attr("data-id");
        delete_private_msg(msg_id_conf);
      }
  });

NOTE: This is an ES6 feature

很抱歉,如果我误解了您的问题,但要获取带有jquery的元素的ID,您可以执行以下操作:

$( ".affirm" ).attr('id')

Is there any chance msg_id_conf and thisid are different types of variables (like one is a String and the other an Int )?

Else, does this work?

  $(".affirm").inlineAffirm({
    callback : function(ele){
        var msg_id_conf = parseInt($(this).attr("data-id"));
        delete_private_msg(msg_id_conf);
      }
  });

If neither of these work, could you please paste the full html tag from class "affirm"?

UPDATE

Try this way then:

  $(".affirm").inlineAffirm({
    var thisid = parseInt($(this).attr("data-id"));
    callback : function(ele){
        var msg_id_conf = thisid;
        delete_private_msg(msg_id_conf);
      }
  });

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