jQuery: How to modify loaded content from inside load callback

99封情书 提交于 2021-01-27 15:12:08

问题


I'm dynamically creating a number of div elements (rows). Every row will have the same basic format, only text changes. As the row structure is complex, I'm trying to load a "basic" div from a static html file, and then once loaded, tweak some of the attributes with each row's params. (Something like Android's xml-defined adapters). I'm using jQuery and jQuery Mobile.

I call this function several times (once per row). On each call I pass as parameters a params object, containing the data for that row, and a newly created div element (created with document.createElement("div")):

    function loadRow(params, div){  
        var $div = $(div);        

        $div.load("some_page.html [data-custom-role=row]", function(){
            //FIXME Throws error: object is not a function!!
            var nameElement = $div("[data-custom-role=name]");
            nameElement.text(params.name);
        });
    }


This code throws this error in the first line below the FIXME comment:

Uncaught type Error: object is not a function


The (simplified) content of the source html file (some_page.html):

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="ISO-8859-1"> 
        </head>
        <body>
            <div data-custom-role="row">
                <p data-custom-role="name"></p>
            </div>
        </body>
    </html>

What I'm trying to do is to select the "p" element inside that newly loaded div, and set the text content. I can't use the id to identify the "p" element because I'll later inject all the rows to the page, and there can't exist 2 elements with the same id. That's why I need to use an attribute as selector, but as many rows would be loading at the same time, I need to make sure I'm only tweaking the "p" element inside the div I'm loading, and not other row divs. I thought the variable $div would be available inside the callback because a closure is created.

What am I doing wrong? How could I query and modify the loaded content inside the callback?

Thanks in advance.


回答1:


You are referencing the DOM element which contains functions but is not a function.

You can't use $div(), you need to use the object's function .find() in your case to find the element with the attribute data-custom-role=name

Try :

   function loadRow(params, div){  
        var $div = $(div);        

        $div.load("some_page.html [data-custom-role=row]", function(){
            $div.find("[data-custom-role=name]").html(params.name);
        });
    }


来源:https://stackoverflow.com/questions/15254228/jquery-how-to-modify-loaded-content-from-inside-load-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!