如何使用jquery在点击的任何位置添加id并删除添加的id

时间:2017-04-03 08:43:58

标签: javascript jquery

我正在尝试单击添加并使用jquery单击删除id函数。

但我在这里有一个问题。

我的添加功能工作正常但我也希望当用户点击任何地方而没有.click按钮时,添加ID应该从.add div类中删除。

我已从codepen.io创建了此 DEMO 。我怎么能这样做,任何人都可以帮助我吗?或者您还有其他方法可以做到吗?

提前致谢。

<div class="container">
   <div class="click" data-id="1">Click HERE</div>

   <div class="add">Check</div>
</div>

JS

$(document).ready(function() {
   $("body").on("click", ".click", function() {
      var ID = $(this).attr("data-id");
      $(".add").attr('id', ID);
      // When you click anywhere i want to remove added
      // $(".add").attr('id', ID);
      // Like this $(".add").attr('id', '');
   });
});

1 个答案:

答案 0 :(得分:1)

试试这个,当你在绿色框外面点击它会从.add类中删除id

&#13;
&#13;
$(document).ready(function() {
   $("body").on("click", ".click", function() {
      var ID = $(this).attr("data-id");
      $(".add").attr('id', ID);
      // When you click anywhere i want to remove added
      // $(".add").attr('id', ID);
      // Like this $(".add").attr('id', '');
   });
});

$(document).mouseup(function (e)
{
    var container = $(".container");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        $(".add").attr('id', '');
    }
});
&#13;
.container {
   position:relative;
   width:100%;
   max-width:300px;
   margin:0px auto;
   padding:25px;
   background:green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
   <div class="click" data-id="1">Click HERE</div>
   
   <div class="add">Check</div>
</div>
&#13;
&#13;
&#13;