jQuery Mouseout问题与REMOVE()方法



我在这里遇到一些困难,理解一个概念。我正在尝试创建一个jQuery脚本,其中鼠标上的div元素上会有一个按钮显示在DIV元素顶部。这部分工作正常。但是,当我鼠标鼠标时,我不确定如何告诉jQuery删除创建的任何按钮。我尝试使用Remove()方法,但是,在Mouseenter上,该按钮未显示。请协助。

html: 您好</button> ->

    <!-- Include JS Files -->
    <script src="js/jquery-1.11.3.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/tag_custom.js" type="text/javascript" charset="utf-8"></script>
</body>

CSS:

.divbutton {
    height: 100px;
    background: #0000ff;
    margin-bottom: 5px;
}

JS:

$(document).ready(function () {
    $(document).on('mouseenter', 'div', function () {
        // check if there's already an added data, if not set status to false
        var status = $(this).data('added') || false;
        // if status is false then create a new element
        if (!status) {
            var tag = $('<button>', {
                text: 'Tagit',
                'class': 'tagit_click',
                click: function(){
                    // TODO: fetch and save data to JSON from here
                    console.log(this);
                }
            })
            // append the element and set the added to true so we don't do that stuff next time
            $(this).append(tag).data('added', true);
        }
    }).mouseout(function(){
        // hide or remove the tagit button on mouseout
    })
});

http://jsfiddle.net/fwg8r/277/

尝试使用.has().is()检查div是否包含.tagit_click元素。

$(document).ready(function () {
    $(this).on("mouseenter", "div", function () {
        // does `div` contain `tagit_click` element ?
        // if not, create `button` element ,
        // append `button` to `div`
        if (!$(this).has(".tagit_click").is("*")) {
            var tag = $("<button>", {
                "text": "Tagit",
                "class": "tagit_click",
                "click": function () {
                    // TODO: fetch and save data to JSON from here
                    console.log(this);
                }
            })
            $(this).append(tag);
        }
    }).on("mouseout", function () {
        // hide or remove `button` on `mouseout`
        $(".tagit_click").detach()            
    })
});

jsfiddle http://jsfiddle.net/fwg8r/280/

最新更新