选择匹配元素

时间:2018-05-07 17:05:21

标签: javascript jquery html

在控制台中,当我点击它时,我试图看到div元素的ID。问题是所讨论的div元素是通过 SCRIPT 创建的。我只能得到第一个div的ID,因为它们是“Mached Elements”但对于其他人来说,我不确定如何获取他们的ID。

如何创建div元素:

$(document).ready(function () {
$.getJSON("/users/12", function (data) {
var socket = new SockJS('/ws-chat');
stompClient = Stomp.over(socket);

$.each(data.rooms, function (i, room) {
//create  chat_card for each room
    var div_card = $('<div class="chat_card" ID=' + room.id + ' onclick="setText()"  style="cursor: pointer;" />');
    console.log(room.id);
    var div_name = $("<div id='h1'/>");
    var nome = jQuery.makeArray(room.name);

        // get each name from room list 
        $.each(nome, function (j, n) {
        var h1 = $('<h1 style="font-size:25px;" class="overflow ellipsis" />');        
        h1.text(n);
        console.log(n);
        div_name.append(h1);
        });

    //image for each room    
    div_card.append('<div><img src="images/profileimage.jpg" class="rounded-circle" style="width: 60px; height:60px; float:left; margin-top:15px; margin-left:20px;"></div>')
    .append(div_name);
    $(".user_chat").append(div_card)
    .append('<hr>');

    //create connection with server
    stompClient.connect({}, function (frame) { 
    setConnected(true);
    console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/room/' + room.id + '', function (greeting) {
        showGreeting(JSON.parse(greeting.body).content);
        });
    });
});
$('#user_profile').append('<h1 id="userone" >' + data.name + '<h1/>');
});    

});

到目前为止我的功能。

function setText(){
           var l = $('.chat_card').attr('ID');
           console.log(l);
        }

1 个答案:

答案 0 :(得分:1)

onclick="setText()"更改为onclick="setText(this)",以便传入已点击的元素。然后将您的方法更改为:

function setText(element){
  console.log(element.id);
}