【问题标题】:jquery data-attribute works randomlyjquery 数据属性随机工作
【发布时间】:2012-12-06 17:07:57
【问题描述】:

我有一个在鼠标移出时调用的函数。 它检查元素现在是否被“拖动”或正在编辑。如果不是,它应该删除活动状态。

这就是它的样子。

function onMouseOut() {
        console.log("mouse out");
        if ($(this).find(".content").attr('data-editing') != "true" && $(this).find(".content").attr('data-dragging') != "true") {
                console.log("no edit, no dragging");
                removeActive($(this).find(".content"));
        } else {
                console.log("edit: " + $(this).find(".content").attr("data-editing"));
                console.log("dragging: " + $(this).find(".content").attr("data-draging"));
        }
}

元素在可排序的内部。它不会破坏上面的代码,我可以根据需要对其进行多次排序。但是当我添加“connectWith”并转移发件人时,它完全崩溃了。

那么我到控制台的输出如下:

mouse out
edit: undefined
dragging: undefined

现在,这怎么可能?

编辑:

好的,标记来了:

<div id="body">
    <section class="main_1 grid_8 field" data-field='main_1'>
        <div class='module'>
        <div class="content content-editor" data-id='1' data-module='content' contenteditable='true'>
            <h1>Heading 1</h1><p>"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
        </div>
        </div>
            <div class='module'>
        <div class="content content-editor" data-id='4' data-module='content' contenteditable='true'>
            <h4>Yet another content</h4><p>This is yet another contentblock!</p>
        </div>
        </div>
    </section>
    <aside class="aside_1 grid_4 field" data-field='aside_1'>
        <div class='module'>
        <div class="content content-editor" data-id='2' data-module='content' contenteditable='true'>
            <h2>Aside Content</h2><p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p>
        </div>
        </div>
    </aside>
    <div class="x-clear"></div>
</div>

这里是js:

    $(document).ready(function() {
    /*
    * - on hoover, we display the panel
    */
    $( ".content-editor" ).mouseenter(onMouseIn);
    $( ".edit-wrap" ).live("mouseleave", onMouseOut);

    /*
    * - on click/focus, we set it as active
    */
    $( ".content-editor" ).focus(onFocus);
    $( ".content-editor" ).blur(onLostFocus);
});


/*
* - functions
*/
function onMouseIn() {
    if ($(this).attr('data-active') != "true" && !dragging) {
        console.log("wasnt active: " + $(this).attr('data-active'));
        makeActive($(this));
    } else {
        console.log("was active: " + $(this).data('id') + " - act: " + $(this).attr('data-active'));
    }
}
function onMouseOut() {
    console.log("mouse out");
    if ($(this).find(".content").attr('data-editing') != "true" && $(this).find(".content").attr('data-dragging') != "true") {
        console.log("no edit, no dragging");
        removeActive($(this).find(".content"));
    } else {
        console.log("edit: " + $(this).find(".content").attr("data-editing"));
        console.log("dragging: " + $(this).find(".content").attr("data-draging"));
    }
}
function onFocus() {
    $(this).attr('data-editing', 'true');
}
function onLostFocus() {
    console.log("lost focus: " + $(this).data('id'));
}
function makeActive($this) {
    $this.attr('data-active', "true");

    $this.wrap("<div class='edit-wrap'>");
    var $parent = $this.parent(".edit-wrap");

    $parent.prepend("<div class='edit-head'>&raquo; Content ( Quick Edit )</div>");
    $parent.append(editMenu);
}
function removeActive($this) {
    $this.parent(".edit-wrap").find(".edit-head").remove();
    $this.parent(".edit-wrap").find(".edit-menu").remove();

    $this.unwrap(".edit-wrap");
    $this.attr('data-active', "false");
}


/*
* - html
*/
var editMenu = "<div class='edit-menu'>"+
        "<a href='#' class='btn openEditor'>Öppna Editor</a>"+
        "<a href='#' class='btn quicksave'>Snabspara</a>"+
        "</div>";

和:

    var dragging = false;

$(document).ready(function() {
    /*
    $( ".edit-head" ).live("mouseover", function() {
        $(this).parent(".edit-wrap").draggable({
            handle: ".edit-head",
            revert: 'invalid'
        }); 
    });

    $( ".edit-wrap" ).live("dragstart", function() {
        $(this).find(".content").attr("data-dragging", "true");
    });
    $( ".edit-wrap" ).live("dragstop", function() {
        $(this).find(".content").attr("data-dragging", "false");
        removeActive($(this).find(".content"));
    });
    */

    $( ".field" ).sortable({
        start: function(e, ui) {
            ui.placeholder.height(ui.item.height());
            $(this).find(".content").attr("data-dragging", "true");
            dragging = true;

            $(".field").addClass("target");

        },
        stop: function() {
            $(this).find(".content").attr("data-dragging", "false");
            dragging = false;

            $(".field").removeClass("target");
        },
        connectWith: '.field',
        placeholder: "drop-placeholder",
        dropOnEmpty: true,
        handle: ".edit-head",

        update: function(e, ui) {
            var $this   = ui.item;
            var $sender = ui.sender;

            if ($sender) {
                //vi bytte field
                console.log("bytte");
            } else {
                console.log("bytte inte");
            }
            console.log("change: " + $this + " from: " + $sender);
        }
    });
});

【问题讨论】:

  • 也发布您的标记
  • 一般来说,您不应该使用.attr('data-foo')。只需使用.data('foo')。还要记住,来自 HTML 标记的数据名称在 jQuery 中总是小写的,无论它们在 HTML 源中是什么大小写。

标签: jquery jquery-ui-sortable


【解决方案1】:

寻找错别字:

attr("data-draging") 

以及代码中的其他地方

attr("data-dragging") 

不过如前所述,请使用:

data("dragging") 

【讨论】:

  • 我将所有数据拖动属性转换为全局“拖动”变量,这似乎可以解决问题。可能的问题是错别字。虽然我不知道如何使用 data() .. (这就是我开始的方式,在我测试以下内容之前它让我很头疼) $("body").attr("data-test", "测试”); console.log("test:" + $("body").data("test")); $("body").attr("data-test", "更多测试"); console.log("test:" + $("body").data("test")); $("body").attr("data-test", "omg more ?"); console.log("test:" + $("body").data("test"));
  • 输出如下: testing testing testing
【解决方案2】:

一方面,我建议不要使用数据属性重载 HTML,而是使用默认属性,例如 idclass(例如,用于活动/拖动状态)。其次,当您一直使用$(this).find() 时,您编写的代码非常慢,您可以在 jQuery 中提供选择器的上下文,还可以缓存您的对象/数据:var $content = $('.content', this);。这使您的代码更清晰($(this).is('.active') 而不是检查数据活动字符串),甚至可能解决编码错误。

PS:如果您使用的是最新的 jQuery 版本,请同时更新您的 jQuery 编码知识 :)(例如阅读文档)

【讨论】:

  • 我非常感谢这个建议。我将检查我的代码并更改为这种方法。但是我不能将其标记为解决方案。
  • 当然不是,我只是注意到一个简单的评论有点长。
【解决方案3】:

我建议您尽可能多地使用数据属性,并保留类主要用于样式化但访问数据属性:

$selector.data("name")

方法而不是

$selector.attr("data-name")

【讨论】:

    【解决方案4】:
    console.log("dragging: " + $(this).find(".content").attr("data-draging"));
    

    错别字,必须是

    console.log("dragging: " + $(this).find(".content").attr("data-dragging"));
    

    这就是你在控制台中得到未定义的原因。

    如果从未设置过 onMouseOut 中的“数据编辑”属性检查,则可能未定义。我默认为假。您可能希望它默认 HTML 元素中的值,或者您可能希望在 if 语句中检查 undefined。

    $( ".content-editor" ).attr('data-editing', 'false');
    

    更改停止以获取事件和ui以及sort(e,ui)并将数据拖动attr ui.item(当前拖动项)设置为false。

     stop: function(e, ui) {
            $(ui.item).find(".content").attr("data-dragging", "false");
            $(this).find(".content").attr("data-dragging", "false");
    

    它没有将您拖动的元素设置为 false,它似乎是为正在移动的元素设置为 false。

    进入“编辑模式”似乎仍然存在问题我不确定模糊是否能很好地处理这个事件。等我有空再更新。

    现在一起来:

      $(document).ready(function() {
        /*
        * - on hoover, we display the panel
        */
        $( ".content-editor" ).mouseenter(onMouseIn);
        $( ".content-editor" ).attr('data-editing', 'false');
        $( ".edit-wrap" ).live("mouseleave", onMouseOut);
    
        /*
        * - on click/focus, we set it as active
        */
        $( ".content-editor" ).focus(onFocus);
        $( ".content-editor" ).blur(onLostFocus);
    });
    
    
    /*
    * - functions
    */
    function onMouseIn() {
        if ($(this).attr('data-active') != "true" && !dragging) {
            console.log("wasnt active: " + $(this).attr('data-active'));
            makeActive($(this));
        } else {
            console.log("was active: " + $(this).data('id') + " - act: " + $(this).attr('data-active'));
        }
    }
    function onMouseOut() {
        console.log("mouse out");
        if ($(this).find(".content").attr('data-editing') != "true" && $(this).find(".content").attr('data-dragging') != "true") {
            console.log("no edit, no dragging");
            removeActive($(this).find(".content"));
        } else {
            console.log("edit: " + $(this).find(".content").attr("data-editing"));
            console.log("dragging: " + $(this).find(".content").attr("data-dragging"));
        }
    }
    function onFocus() {
        $(this).attr('data-editing', 'true');
    }
    function onLostFocus() {
        console.log("lost focus: " + $(this).data('id'));
        //$(this).attr('data-editing', 'false');
    }
    function makeActive($this) {
        $this.attr('data-active', "true");
    
        $this.wrap("<div class='edit-wrap'>");
        var $parent = $this.parent(".edit-wrap");
    
        $parent.prepend("<div class='edit-head'>&raquo; Content ( Quick Edit )</div>");
        $parent.append(editMenu);
    }
    function removeActive($this) {
        $this.parent(".edit-wrap").find(".edit-head").remove();
        $this.parent(".edit-wrap").find(".edit-menu").remove();
    
        $this.unwrap(".edit-wrap");
        $this.attr('data-active', "false");
    }
    
    
    /*
    * - html
    */
    var editMenu = "<div class='edit-menu'>"+
            "<a href='#' class='btn openEditor'>Öppna Editor</a>"+
            "<a href='#' class='btn quicksave'>Snabspara</a>"+
            "</div>";
    
    
      var dragging = false;
    
    $(document).ready(function() {
        /*
        $( ".edit-head" ).live("mouseover", function() {
            $(this).parent(".edit-wrap").draggable({
                handle: ".edit-head",
                revert: 'invalid'
            });
        });
    
        $( ".edit-wrap" ).live("dragstart", function() {
            $(this).find(".content").attr("data-dragging", "true");
        });
        $( ".edit-wrap" ).live("dragstop", function() {
            $(this).find(".content").attr("data-dragging", "false");
            removeActive($(this).find(".content"));
        });
        */
    
        $( ".field" ).sortable({
            start: function(e, ui) {
                ui.placeholder.height(ui.item.height());
                $(this).find(".content").attr("data-dragging", "true");
                dragging = true;
    
                $(".field").addClass("target");
    
            },
            stop: function(e, ui) {
                $(ui.item).find(".content").attr("data-dragging", "false");
                $(this).find(".content").attr("data-dragging", "false");
    
                dragging = false;
    
                $(".field").removeClass("target");
            },
            connectWith: '.field',
            placeholder: "drop-placeholder",
            dropOnEmpty: true,
            handle: ".edit-head",
    
            update: function(e, ui) {
                var $this   = ui.item;
                var $sender = ui.sender;
    
                if ($sender) {
                    //vi bytte field
                    console.log("bytte");
                } else {
                    console.log("bytte inte");
                }
                console.log("change: " + $this + " from: " + $sender);
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多