1

I have the below JS code

for(var i=0;i<resultData.length;i++) {
    var id = "" + counter + "_" + resultData[i].id;
    var action = resultData[i].action;
    str += "<li id=" + id + "><div id=div_" + id + "><img src='assets/img/plus.png' id='img_" + id + "' onclick=getSubDirs('" + id +"', '" + action +"') /><label id=label_"+ id +" onclick=clickedDir('"+ id + "')>"+ resultData[i].label + "</label>" +"<span style='display:none' id=path_"+ id +">"+ resultData[i].path +"</span></div></li>";
    counter++;
}

The above code generates a dynamic list and I'm adding it to ul.

<li id="id_1_abc">
    <div id="div_id_1_abc">
        <img src="assets/img/plus.png" id="img_id_1_abc" onclick="getSubDirs('id_1_abc'," 'job')="">
        <label id="label_id_1_abc" onclick="clickedDir('id_1_abc')">abc</label>
        <span style="display:none" id="path_id_1_abc">/abc</span>
   </div>
</li>

The above is the generated list. But my onlick changes to onclick="getSubDirs('id_1_abc'," 'job')=""

2
  • try use \" as str += "<li onclick="\func('" + var + "')"\></li>" Commented Oct 26, 2018 at 5:02
  • try using jquery event handler .on js api.jquery.com/on Commented Oct 26, 2018 at 5:04

2 Answers 2

1

Using backticks will make this way more readable. Your problem is that you need to wrap the onclick handler in quotes:

str += `<li id="${id}"><div id="div_${id}"><img src='assets/img/plus.png' id="img_${id}" onclick="getSubDirs('${id}', '${action}') />...`
Sign up to request clarification or add additional context in comments.

Comments

0

Could be duplicated to Event handler not working on dynamic content

use jquery .on function

<ul id="someidname">
  **dynamic content **
  <li class="someclassname" id="id_1_abc">
    <div id="div_id_1_abc">
        <img src="assets/img/plus.png" id="img_id_1_abc" >
        <label id="label_id_1_abc" >abc</label>
        <span style="display:none" id="path_id_1_abc">/abc</span>
   </div>
</li>
</ul>

on your js

$("#someidname").on('click','.someclassname', function(){
// yourfunctions ..
// clickedDir()
// getSubDirs()
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.