检查div是否有附加元素

时间:2016-01-12 13:32:28

标签: jquery if-statement



$("#add").click(function() {
  var userValue = $('#textarea').val();
  $('#textarea').val('');
 $('#writtings').append('<p>' + userValue + '</p>');

});

$('body').on('click', '#delete', function() {
     $("#writtings p").remove();
     return false;  
  });
  
 if($('#writtings').is(':empty') ) {
  $("#delete").css("background","red");
 }else {
   $("#delete").css("background","green");
 }
&#13;
#writtings {
  margin-top:20px;
  width:200px;
  height:auto;
  border:1px solid #333;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea  id="textarea" placeholder="Write here!"></textarea>    
 <button id="add">Add</button>
 <button id="delete">Delete</button>
 <div id="writtings"></div>
&#13;
&#13;
&#13;

伙计们,我想检查我的div是否附加了元素。如果有附加元素,我会改变我的按钮背景。那么如何?JsFiddle

3 个答案:

答案 0 :(得分:1)

$("#add").click(function() {
    var userValue = $('#textarea').val();
    $('#textarea').val('');
    $('#writtings').append('<p>' + userValue + '</p>');
     if($('#writtings p')) {
        $("#delete").css("background","red");
     } 
     else {
     $("#delete").css("background","green");
     }
});

$('body').on('click', '#delete', function() {
     $("#writtings p").remove();
     $("#delete").css("background","green");
     return false;  
  }); 

https://jsfiddle.net/qxx50up8/1/

答案 1 :(得分:0)

$("#delete").css("background","green")按钮的点击事件中添加add,如下所示。

$("#add").click(function() {
    var userValue = $('#textarea').val();
    if(!userValue) retrun;

    $('#textarea').val('');
    $('#writtings').append('<p>' + userValue + '</p>');

    $("#delete").css("background","green");
});

$("#delete").css("background", "red");按钮的点击事件中添加delete,如下所示。

$('body').on('click', '#delete', function() {
    $("#writtings p").remove();
    $("#delete").css("background", "red");

    return false;  
});

答案 2 :(得分:0)

在您的情况下,您可以通过以下代码检查p tag是否附加到#writtings div: -

  if($('#writtings').find('p').length == 1 ) {
          $("#delete").css("background","red");
         }else {
           $("#delete").css("background","green");
    }