我想更改并验证html的h2标记的值。我把它放在一个div。什么当前的情况是,当我按下h2标签,它会自动打开一个文本框,我可以编辑/清除文本框的值。
问题:当我尝试清空文本框值时,它不会在运行时生成错误消息。但是,当我单击我的jsp文件时,会产生错误消息。下面是一个示例代码。
<div class="modal-header">
<h2 class="tc_pageheader editableName" id="detailsheader"></h2>
</div>
在我的情况下,当id值为空时,它必须显示一个错误消息,h2标签不能为空。我想通过使用jQuery (v1.9)验证来实现这一点。
由于没有太多的代码要继续,我做了一个我认为你要做的模拟。
演示:http://jsfiddle.net/NnkRV/
代码:$(document).on('click', '#detailsheader', function() {
$(this).replaceWith("<input type='text' id='edit' value='" + $(this).text() + "' />");
});
$(document).on('focusout', '#edit', function() {
var newTitle = this.value;
if (newTitle == '') {
alert("Cant be blank!");
return false;
}
else {
$(this).replaceWith('<h2 class="tc_pageheader editableName" id="detailsheader">' + newTitle + '</h2>');
}
});
这只允许您编辑H2的标题,如果有空白标题则显示错误。