简体   繁体   中英

dojo dynamically connect onclick event to drop down list item

I have a search box sending ajax request to create a dropdown list of items from the JSON responseText. I want to link each item to an "onclick" event. However, using the code below, all my events happend at the same time (not even on click) once my dropdown list appears.

function getDropDownList(jso){
    if (jso.errorCode == 0){
        var result = document.createElement("div");
            result.className = "resultList";

        for (var i = 0 ; i < jso.resultats.length && i < 7; i++){
            var item           = document.createElement("div");
                item.className = "item";
                item.innerHTML = jso.results[i].name + ' (' + jso.results[i].localities + ')';

            result.appendChild(item);

            dojo.connect(item, 'onclick', myEventHandler);
        }
     myToolBar.appendChild(result);
     }
}

Can someone help me to figure out what's wrong with this scheme ?

I recommend to use dojo/on and AMD load.

//this is a way
require(["dojo/query","dojo/domReady!"], function(query){
    //Use "dojo/request" if you need Send a request.
    var result  = dojo.create("div", {class:"resultList"}, null);
    //for()...... or import "dojo/_base/array" and make forEach
    query(dojo.create('div',
                    { innerHTML: jso.results[i].name + ' (' + jso.results[i].localities + ')',
                  class:"item"//other parameters here!.
                            }, null))
    .onclick(function(e){ console.log('clicked', e.target); })//or call myEventHandler
    .place(result);
    //End for
    query(result).place('#myToolBar');//add result to Dom element with id myToolBar
    });

More information on Dojo events can be found here .

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM