【问题标题】:Know which user created div was clicked知道点击了哪个用户创建的 div
【发布时间】:2016-03-25 15:06:37
【问题描述】:

如果我的解释难以理解,我深表歉意。 使用此代码:

names.push(newName);
var strName = newName;
var newName = document.createElement('p')
newName.setAttribute('id', newName);
document.body.appendChild(newName);
newName.innerText = strName;
$(newName).css('position','absolute')
$(newName).css('top', y);
$(newName).css('left', x);
updateXY();

用户创建了一个新的 div(使用用户输入的名称),它可以正常工作。 我的问题是我不知道如何知道何时单击了这些用户创建和命名的 div 之一。

例如:

如果用户创建了 2 个 div,'hello' 和 'goodbye' 我不能只使用 $('#hello').click(function() {});等等,因为我不知道用户会选择创建名为“hello”的 div

此外,数组名称包含所有 div 的所有名称 - 如果这对任何人有帮助的话。谢谢,任何帮助表示赞赏

【问题讨论】:

  • 为什么不创建这个带有前缀的 div,比如“userCreated”,这样你就知道所有以该名称/ID 开头的 div 都属于用户创建的?
  • 为什么不使用 add common class to all divs 并添加$(document).on('click', 'common-class', function() { });

标签: javascript jquery html css arrays


【解决方案1】:

只需将事件侦听器添加到元素,就像您在设置元素时所做的那样:

 $(newName).on("click",function(){
   console.log("element "+$(this).text()+" clicked");
 });

JSFiddle

或者,用JS的addEventListener()

newName.addEventListener("click",function(){});

JSFiddle

或者,旧浏览器的旧方式,onclick

newName.onclick = function(){};

JSFiddle

【讨论】:

    【解决方案2】:

    你可以这样做

    $(newName).on("click",function(e){
        // the variable 'e' is the event of click, if we do e.toElement, we get to know who the element clicked is
        var $thisDiv = $(e.toElement);
        // do something with $thisDiv
    });
    

    【讨论】:

      【解决方案3】:

      创建 div 元素后,需要在 div 上初始化 'click' 事件

      <a class="js-create-div" href="#">Create Div</a>
      
      $(document).ready(function(){
          function init(){
            var newUserDiv = $(".js-user-div").not(".js-inited");
      
            newUserDiv.on("click",function(){
      
              alert($(this).html());
      
            });
      
            newUserDiv.addClass("js-inited");
          }
      
          $(".js-create-div").click(function(){
          $("#wrapper").append("<div class='js-user-div'>"+Math.random()+"</div>");        
          init();
        });
      });
      

      https://jsfiddle.net/ema0nazs/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-18
        • 1970-01-01
        • 2011-07-17
        相关资源
        最近更新 更多