Jquery如果contenteditable=true事件

3

我正在尝试检测所点击的元素是否具有contentEditable属性。我已经尝试了以下代码:

$( "#thediv" ).hide();    
$(this).click(function() {
    if ($(this).is("[contenteditable='true']")) {
    return true;
    $( "#thediv" ).show();
    alert('hi');
} else if ($(this).is("[contenteditable='false']")) {
    return false;
    $( "#thediv" ).hide();
    alert('hi');            
}
}); 

$( "#thediv" ).hide();  

$(this).click(function() {
    if ($(this).attr("contentEditable") == true) {  
        $( "#thediv" ).show();
        alert('yes');
    } else {
        $( "#thediv" ).hide();  
        alert('no');          
    }    
}); 

如何让它发挥作用?

这是一个代码片段

4个回答

9
contenteditable 属性可以告诉您元素是否具有明确的可编辑值。但是,可编辑性是继承的。因此,在下面的 HTML 中,<span> 元素是可编辑的,但没有 contenteditable 属性值:
<div contenteditable="true"><span>Some editable text</span></div>

你需要使用的是isContentEditable属性,它恰好可以满足你的需求:
$(this).click(function() {
    if (this.isContentEditable) {
        // Do stuff
    }
});

3

这个是未定义的。看这里 http://jsfiddle.net/dqEE2/2/

$( "#hello" ).hide();  
$(function() {
    $("div").click(function() {
        if ($(this).attr("contentEditable") == "true") {
            $( "#hello" ).show();
            alert("yes");
        } else {
            alert("no");
          $( "#hello" ).hide(); 
        }
    });

1

你尝试过使用jQuery的attr吗?http://api.jquery.com/attr/可能会起作用。

if ($(this).attr("contentEditable") == "true") {

编辑:以下代码完全正常:

if ($(this).is("[contentEditable='true']")) {

afro360的问题与众不同


@afro360 我把 true 改成了 "true",现在它对我来说可以工作了。 - Felk
你只是将事件添加到了隐藏元素上。我怎么能够点击它呢?看看这个:fiddle - Felk
在我的fiddle中,当我点击contenteditable时,我想显示#hello。如果您单击的div不是contenteditable,则希望隐藏#hello。 - afro360
如果我刪除了第一個$( "#hello" ).hide();,它就會隱藏,但當我點擊contenteditable時,它不會顯示。 - afro360
然后将$(this).click(function() ...替换为类似于$("#test").click(function() ...的内容,该内容将点击事件监听器添加到隐藏事件中。 - Felk

0

使用 element.isContentEditable 将是最简单的解决方案。

$(".edit").on("click", function() {
  var status = document.getElementById("theContent").isContentEditable;
  $("#theContent").prop("contenteditable", !status);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接