找不到的DOM元素与AJAX加载后(要绑定的jQuery插件的话)的话、找不到、绑定、插件

2023-09-10 16:37:17 作者:100%纯情

所以,我有2个HTML页面。 1是和用作容器1,其功能如同内容。 当我有一个表加载网页的内容我能使用拖放。

So I have 2 html pages. 1 that functions as container and 1 that functions as content. When I load the content page with a table I'm able to use drag and drop.

但是,当我去我的容器页面并加载网页的内容与阿贾克斯,拖放一个div停止工作。内容页内的所有其他JavaScript功能仍然有效。我怎样才能jQuery的DND插件绑定到装有阿贾克斯表?

But when I go to my container page and load the content page into a div with ajax, the drag and drop stops working. All other javascript functionalities inside the content page still work. How can I bind the jquery dnd plugin to the table loaded with ajax?

我使用拖放放大器;这一下降,因为教程http://isocra.com/2008/02/table-drag-and-drop-jquery-plugin/

I'm using drag & drop with this as tutorial http://isocra.com/2008/02/table-drag-and-drop-jquery-plugin/

我的code是这样的:

my code looks like this:

$(window).load(function()
{   if(temp == 0)
    { 
        DP("eerste keer")
        load_table(); 
        temp = 1;
    }
} );

function load_table()
{    
    DP('load_table');
    $.ajax({
            //async: false,
            type: "POST",
            url: "/diagnose_hoofdpagina/table_diagnose/" + DosierID, // <== loads requested page
            success: function (data) {
                    $("#diagnoses_zelf").html(''); //<== clears current content of div
                    $("#diagnoses_zelf").append(data).trigger('create'); // <== appends requested page
                },
            error: function(){
                alert('error');
              } 
        }).done(function() {
        update_table(); 
        initialize_table();    // <== calls jquery plug in
        });

    return false;   
}


function initialize_table() 
{
    var tableid = $('#diagnoses_zelf table').attr('id'); //< this finds the correct table thanks to Fábio Batista => this option worked, rest didn't
    alert(tableid);
    $(tableid).tableDnD({    
        onDrop: function(table, row) {
        alert(table + "     "  +  row);

        },
        onDragStart: function(table,row){
        var tette = $(row).index;
        alert(tette);
        },
        dragHandle: ".dragHandle"
    });     
}

这怎么是可能的,我能做些什么呢? 任何人都可以帮我这个吧。

How is this possible and what can I do about it? Can anyone help me with this please.

极短的: 我想访问表中的我加载到我的容器页面Ajax和使用jQuery的拖放插件上的ID。

Very short: I want access to the ID of the table I load into my container page with ajax and use the jquery drag and drop plug in on it.

修改

结果:的

不知怎的,我在容器页表得到了重新命名为 pSqlaTable ,而不是我的ID在控制器页面,该页面是给了它。

Somehow my table in the container page got renamed to pSqlaTable instead of the id I gave to it in the controller page which is.

<table id="tableDiagnose" class="table table-hover">

这就是为什么在code找不到表annymore得到修复此code感谢法比奥·巴蒂斯塔:

Thats why the code couldn't find the table annymore Got fixed by this code thanks to Fábio Batista:

$('#diagnoses_zelf table').tableDnD( ... );

,但我怎么能现在使用DND插件?

, but how can I use the dnd plugin now ?

它找到表了,但我还是没能免打扰插件绑定到它,我是能够绑定一个jQuery插件阿贾克斯装表?

修改

//drag & drop http://isocra.com/2008/02/table-drag-and-drop-jquery-plugin/
function initialize_table() 
{
    var tableid = $('#diagnoses_zelf table').attr('id');
    alert(tableid);
    $('#' + tableid).tableDnD({    
        onDrop: function(table, row) {
        alert(table + "     "  +  row);

        },
        onDragStart: function(table,row){
        alert('issemer?');
        },
        dragHandle: ".dragHandle"
    });    
} 

这是在code我仍然坚持。 TABLEID是正确的,但jQuery的的初始化是没有的。我不能拖drows在表中。是我的语法错误?

This is the code i'm still stuck with. tableid is correct but the initialisation of the jquery isn't. I can't drag the drows in the table. Is my syntax wrong ?

修改

难道是我不能jQuery的绑定表,因为我dynamicaly产生与ZPT(或javascript)?其他页的表格

推荐答案

您正在混合大量的外部库和code的。这导致可能的版本之间有很多的黑匣子在code错配和。

The issue with plugins.

You're mixing lots of external libraries and code. This results in possible mis-matches between versions, and a lot of black boxes in your code.

作为一个开发者,这应该让你感到很不安。有code你不完全理解你的code基可以得到很无奈的真快。

As a developer, this should make you feel very uneasy. Having code you do not fully understand in your code base can get really frustrating really fast.

通常情况下,这些种类的插件提供的功能,我们作为JavaScript开发人员可以实现很容易,没有他们。这一发展过程中,再简单不过的场景,让我们一起创造code,我们理解并能够更轻松地维护。我们不仅从这个过程中学习,但我们也创造了特定的code小位。社区驱动的解决方案是在总体非常好,但要记住他们不是银弹这一点很重要。你经常使用就完蛋了这对您的特定情况下的错误不那么活跃的项目,你必须挖通一个大的,不熟悉的code基地。

Often, these sort of plugins provide functionality we, as JavaScript developers can accomplish just as easily without them. This development process, in simple enough scenarios, lets us create code we understand and have an easier time maintaining. Not only do we learn from this process, but we also create smaller bits of specific code. Community driven solutions are very good in general, but it's important to remember they're not a silver bullet. Often you're stuck using a not-so-active project which has a bug for your specific case and you have to dig through a large, unfamiliar code base.

那么,这拖放插件吗?

嗯,我会分解如下:

侦听的鼠标按下上表中的行事件 当这样的事件触发,开始移动表行相匹配的鼠标位置 在mouseup发生时,检测到,并最终确定了位置。

让我们看看我们如何能够做同样的事情。 假设表的HTML是这样的:

Let us see how we can do something similar. Let's assume the table's HTML is something like:

<table>
    <tbody>
    <tr>
        <td> Hello 1</td>
    </tr><tr>
        <td> Hello 2</td>
    </tr>
    </tbody>
</table>

下面是一些基本的样式应用桌上的小提琴

接下来,我们将听选择事件。我们将添加一个事件表中的行选择和到文档时鼠标了。 jQuery有事件监听此类事件。因为我们希望这些活动要坚持,即使AJAX,我们将使用 。对 < /一>,它可以让我们使用委托的事件。 。对也就是说,即使我们将内容添加到表后,都不会有问题。

Next, we'll listen to the selection events. We'll add an event to the table rows for selection and to the document to when the mouse is up. jQuery has event listeners for such events. Since we want these events to stick even after AJAX, we'll use .on which lets us use delegated events. .on means that even if we add content to the table later, it won't matter.

var selected; // currently selected row
$(document).on("mousedown","#MySpecialTable tr",function(){
   $("#textDiv").text(this.textContent); 
    selected = this;
});
$(document).on("mouseup",function(){
    $("#textDiv").text("Left "+selected.textContent); 
    selected = null;
});

这里是这样的code工作小提琴。

现在,我们要真正改变拖动和放大器;下降上班的时候,也就是更新当前位置到一个反射鼠标位置。我们可以听鼠标移动事件,并发现我们目前的元素。类似于

Now, we'll want to actually change the drag&drop to work when, that is, update the current position to the one reflecting the mouse position. We can listen to mousemove events, and detect the element we're currently on. Something like

$(document).on("mousemove",function(e){
    $("#textDiv").text($(e.target).html());
});

你可以在这里看到的工作小提琴

这是很好的,但我们要真正改变元素位置。所以,我们需要改变的表结构允许的。我们可以删除元素,并在正确的位置,将其追加。我们会检查,如果我们有一个选择的元素,如果我们这样做,我们可以跟踪它相比,在鼠标移动事件中的当前元素。我们可以首先检测是否我们应该像拖:

That's nice, but we want to actually change the element position. So we'll need to change the table structure to allow that. We can remove the element, and append it at the correct position. We'll check if we have a selected element, and if we do, we can track it compared to the current element in the mousemove event. We can for starters detect if we should drag with something like:

$(document).on("mousemove",function(e){
    if(selected !=null){// got an element selected
        if($("#MySpecialTable").has(e.target).length > 0){ //in the table
            $("#mousePos").text("DRAGGING");    
        }
    }else{
        $("#mousePos").text("NOT SELECTED");
    }
});

(小提琴)

现在,我们将添加实际的选择,我们将更换元件当目标不是我们的元素,我们在表中。我们完全code应该是这样的:

Now, we'll add actual selection, we'll replace the elements when the target is not our element and we're in the table. Our full code should be something like:

var selected;
$(document).on("mousedown","#MySpecialTable tr",function(e){
    e.preventDefault();//stop the text selection;
   $("#textDiv").text(this.textContent); 
    selected = $(this);
    selected.find("td").css("background-color","#999");
});
$(document).on("mouseup",function(){
    $("#textDiv").text("Left "+selected.text()); 
    selected.find("td").css("background-color","");
    selected = null;
});
$(document).on("mousemove",function(e){
    if(selected !=null){// got an element selected
        if($("#MySpecialTable").has(e.target).length > 0){ //in the table
            var el = $(e.target).closest("tr");//the tr element we're on
            el.before(selected);// replace the elements
        }
    }else{
        $("#mousePos").text("NOT SELECTED");
    }
});

$("#MySpecialTable").on('selectstart', false);//Don't let the user select the table

(小提琴)

现在,到目前为止我们只有code,这是很好的,因为我们确切地知道发生了什么,也不需要使用大量的外部code线,我们不完全的几行明白了。

Now, so far we only have a few lines of code, which is nice since we know exactly what's going on and didn't need to use lots of lines of external code we don't fully understand.

但它会AJAX?

让我们将数据加载到表与AJAX吧!我们将使用模拟一个AJAX响应的setTimeout 这将允许我们模拟一个异步请求。我们将使用

Let's load the data into the table with AJAX and see! We'll simulate an AJAX response using a setTimeout which would allow us to simulate an asynchronous request. We'll use

setTimeout(function(){
    $("#MySpecialTable").html("<tr><td> Hello 1</td></tr><tr><td> Hello 2</td></tr><tr><td> Hello 3</td></tr><tr><td> Hello 4</td></tr><tr><td> Hello 5</td></tr><tr><td> Hello 6</td></tr>");
},1000);

这意味着,在一秒钟后更新 #MySpecialTable 的HTML。让我们来看看它是否工作好吗?

This means, update the HTML of #MySpecialTable after one second. Let's see if it works shall we?

那么,为什么它的工作原理?很好,我们用的委托如果我们加载元素在屏幕右侧现在还是不是,这意味着我们不关心事件。我们有洞察力要做到这一点,因为我们建立我们的C自己$ C $,知道我们的最终目标是。剩下要做的唯一事情是干净codeA一点。

So why does it work? well, we used delegated events which means we don't care if the elements we're loading are in the screen right now or not. We had the insight to do this since we built our code ourselves and knew what our final goal was. The only thing left to do is clean the code a little.

我们要我们的包装code以下,以prevent $免受非冲突模式的问题(也就是$已经采取的页面:

We'll wrap our code in the following, to prevent $ from being an issue in non-conflict mode (that is, $ is already taken in the page:

(function($){

})(jQuery);

接下来,我们将增加我们的表事件绑定:

Next we'll add a binding for our table event:

$.GertVDragTable = function(elementSelector){ // rest of code.

最后,我们的code可能是这个样子。

使用它,将是一个简单的 $ GertVDragTable(#MySpecialTable); 或者,我们也可以把它放在 $ FN ,让每一个函数来调用它。这是一个品味的问题。

Using it, would be a simple $.GertVDragTable("#MySpecialTable"); alternatively, we can put it on $.fn and allow every function to call it. Which is a matter of taste.

没有复制面食请:)我倒是AP preciate它,如果你停止每一个阶段,并认为的为什么的下一个步骤是。

No copy-pasta please :) I'd appreciate it if you stop on every stage and think why the next step was taken.