禁止使用jquery向DIV添加HTML元素

Disable adding HTML elements to the DIV using jquery

本文关键字:添加 HTML 元素 DIV jquery 禁止      更新时间:2023-09-26

这是代码

<div id="whatever">
/* I have setted up a button to enter html code in this div via jquery*/
/* Now I want to devise another button which will disable further addition addition to the div elements with the previous html as it is*/
</div>

我该怎么做?除了jquery(可能是CSS),还有其他方法吗。我试过了:

$(".whatever").attr("disabled", "disabled");
$(".whatever").prop("disabled", "disabled");

经过进一步的研究,我发现只有表单元素才具有禁用属性。

我认为这是一种比直接添加和删除属性更干净的方法。

$("div *").disable();

演示

"div"元素没有"禁用"状态。您可以做的是,您可以在Javascript中使用类似"isEditable"的布尔变量,并将其设置为相应的状态。例如:

JS Fiddle在这里:http://jsfiddle.net/weM57/

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
    var isEditable = true;
    $("#btnAdd").click(function() { 
        if (isEditable) {
            $("#whatever").append("<p>this is some content</p>");
        } else {
            $("#status").html("<p>The div is not editable at the moment</p>");
        }   
    });
    $("#btnDisable").click(function() { 
        isEditable = false;
        $("#status").html("<p>The div is not editable anymore</p>");
    });
    $("#btnEnable").click(function() {  
        isEditable = true;
        $("#status").html("<p>The div is editable now</p>");
    });
});
</script>
</head>
<body>
    <input type="button" id="btnAdd" value="Add Content" />
    <hr />
    <input type="button" id="btnDisable" value="Disable Content Adding" />
    <input type="button" id="btnEnable" value="Enable Content Adding" />
    <hr />
    <div id="whatever">
    </div>
    <div id="status" style="border: dotted 1px gray; background-color: yellow; padding: 20px;">
    </div>
</body>
</html>

当您单击要禁用div的按钮时,向div添加一个类,例如disabled。。。然后在适当的代码中检查这个类,看看它是否存在,如果存在,不要向它添加任何内容…

大致如下:

$('.addButton').click(function(){ 
   if ($('#whatever').hasClass('disabled'))
      return false;
   // your code here
});
$('.disableButton').click(function(){
    $('#whatever').addClass('disabled')
});

这是正在工作的FIDDLE。

通过点击"添加html"按钮,它会将html添加到div中,通过点击"禁用"按钮,当你点击"添加html"按钮时,它会禁用div,你将无法向其中添加新的html,我还添加了"启用"按钮,只是向你展示如何在你需要它的情况下执行