简体   繁体   中英

How to add o'clock event the append html code using jQuery?

Below is my code trying to add some html to page...

$('#DocUploadDiv').append(
    '<div class="uploadClick" style="float:left; margin-right: 10px; margin-bottom: 10px">' + 
    '<i class="fa fa-times fa-remove"></i>' +
    '<i class="fa fa-plus-circle fa-2x" onclick="$("#DocUpload").click()"></i>' + 
    '<div>'
);

I can get correct div style on my page when using this jQuery code.

However, the onclick event is not working.

How to add onclick event when append html code using jQuery?

Look at your quotes. You have

`'....onclick="$("#DocUpload").click()"...`

Where does that attribute end? Answer: Here:

`'....onclick="$("#DocUpload").click()"...`
// --------------^

because that's the first " after the opening " .

You can fix it in at least two ways: By using a ' and escaping it (since this is all in a string delimited by ' ):

`'....onclick="$(\'#DocUpload\').click()"...`
// --------------^^----------^^

or since the text in onxyz handlers is HTML (although people tend to forget that), you could use the named character entity &quot; :

`'....onclick="$(&quot;#DocUpload&quot;).click()"...`
// --------------^^^^^^----------^^^^^^

But better still would be to use modern event handling:

  1. Ditch the onclick attribute entirely

  2. Add a semantic class to that i element, such as trigger-upload

  3. Use delegated handling:

     $(document).on("click", "#DocUploadDiv .trigger-upload", function() { $("#DocUpload").click(); });

Even better than that would be to have both elements call the same function, rather than doing a synthetic click:

function handleUpload() {
    // Do whatever you're doing in the #DocUpload click handler now
});
$("#DocUpload").click(handleUpload);
$(document).on("click", "#DocUploadDiv .trigger-upload", handleUpload);

Or even:

$(document).on("click", "#DocUploadDiv .trigger-upload, #DocUpload", function() {
    // Do whatever you're doing in the #DocUpload click handler now
});

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