禁止使用jquery向DIV添加HTML元素
Disable adding HTML elements to the DIV using jquery
这是代码
<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,我还添加了"启用"按钮,只是向你展示如何在你需要它的情况下执行
相关文章:
- 使用jQuery根据动态生成的html动态添加html
- 如何使用javascript选择字符串的部分,添加html标记或删除部分
- 单击按钮添加HTML表单
- 如何添加html<br>标记转换为javascript
- 动态添加 HTML 元素后创建 jQuery 事件
- 在具有特定ID的DIV中使用JavaScript动态添加HTML元素
- 在前面的输入元素之前添加html输入元素
- 程序添加html后点击不工作
- 使用appendchild或其他方法向ul添加html代码而不是纯文本
- 如何在JS函数中添加HTML代码
- Jquery从另一个页面添加HTML
- 如何在不添加html脚本标记的情况下使用google-maps-api-v3
- 正在尝试向jQuery对象添加HTML类属性
- 使用“添加用户”按钮添加HTML字段
- 在 JavaScript 中的 textNode 中添加 html
- jquery动态添加HTML字段遇到了神秘的问题
- AngularJS 如何动态添加 HTML 并绑定到控制器
- 使用 js 添加 HTML 元素
- 在 JavaScript 切换中添加 html / css
- 如何在 tinymce 的第一段中添加 html 链接