Search code examples
javascriptdom-eventsblackberryblackberry-webworks

Add link element in div tag with looping


I want to make my DIV element to be able to click and go to the detail page with the ID as a query parameter data to my server. I have found some examples of possible uses I can use, example :

<div style="cursor:pointer;" onclick="document.location='http://www.google.com'">Foo</div>

It's just that I was confused would like to add the above script into the code that I built.

Part of my code :

    for ( var i = 0; i < response.length; ++i ) {
                str = response[i].judul;
                str2 = response[i].waktu_mulai;
                str3 = response[i].channel_code;


                var Year,Month,Date,Time,Strip,Join= ""

                var Year        = str2.substr(0,4)
                var Month       = str2.substr(5,2)
                var Date        = str2.substr(8,2)
                var Time        = str2.substr(-8,8)
                var Strip       = str2.substr(4,1)

                var Join        = Date+Strip+Month+Strip+Year+' '+Time

                listItem = document.createElement('div');
                listItem.setAttribute('data-bb-type', 'item');
                listItem.setAttribute('data-bb-img', 'images/icons/logo/'+str3+'.png');
                listItem.setAttribute('data-bb-title', str);
                listItem.innerHTML = Join+" WIB";
                container = document.createElement('div');
                container.appendChild(listItem);
                bb.imageList.apply([container]);
                dataList.appendChild(container.firstChild);  
                        if (bb.scroller) {
                                bb.scroller.refresh();
                        }
}

Maybe someone can help me use the link on each DIV additions made ​​by looping my application from database.


Solution

  • Using just this will solve your problem I think:

    <element>.setAttribute('onclick','doSomething();'); // for normal browsers
    <element>.onclick = function() {doSomething();}; // for IE
    

    where you can replace 'doSomeThing();' with your own wanted code eg. : "document.location='http://www.google.com'"

    If you want to make it more dynamic, you can also just call a function:

    <element>.setAttribute('onclick','myFunction();'); // for normal browsers
    <element>.onclick = function() {myFunction();}; // for IE
    

    Where myFunction:

    function MyFunction() {
        var called_id = this.id;
        var call_url = "http://myurl.com/page?id="+called_id;
        document.location = call_url;
        return; //superflous 
    }