簡體   English   中英

使用動態創建的DOM元素在點擊時添加樣式

[英]Add styling on click with dynamically created DOM elements

我想在選中div內包含的圖像周圍創建邊框,然后在取消選中它時將其刪除。 如何獲取所選div的ID?

 function displayLive()
            {
              var previous = null;
              var current = null;
              setInterval(function()
              {
                $.ajax({
                  url: '/showLive',
                  dataType: 'json',
                  contentType: 'application/json',
                  success: function(response) 
                  {
                    current = JSON.stringify(response);
                    if(previous !== current)
                    {
                      var obj = JSON.parse(response);
                      console.log(obj);
                      for(var i = 0; i < obj.active.length; i++)
                      {
                        if($(document.getElementById(obj.active[i].userNameData)).length == 0)
                        {
                          if(obj.active[i].active === true)
                          {
                            $('.left').prepend($('<div/>', {class: 'profTemp', id: obj.active[i].userNameData}).append(
                              $('<img/>', {src: obj.active[i].profiler, width: 40, height: 40}),
                              $('<span/>', {text: " " + obj.active[i].userNameData}))); 
                          }  

                        }
                        else if(obj.active[i].active === false)
                        {
                          $(document.getElementById(obj.active[i].userNameData)).remove();
                          console.log("getting in false");
                        }
                      }
                    }
                  }
                }); 
                previous = current; 
              }, 2000);   
            }

這是一個模板

通過$(document).on('click', '.profTemp', function() {})分配點擊處理程序$(document).on('click', '.profTemp', function() {})以觸​​發文檔上的click事件,以便它將與動態添加的元素一起使用,然后在div並將其用作是否單擊狀態,並引用該類以繪制邊框。

 $('body').append('<div class="profTemp"> <img class="img" src="https://i.stack.imgur.com/2C22p.jpg"></div>'); $(document).on('click','.profTemp',function() { $(this).toggleClass('selected'); }) 
 .profTemp { display: inline-block; } .selected img { border: 5px solid red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM