简体   繁体   中英

DOM object loses reference after passing through jquery functions

Something odd has occured to me with an object reference.

I have the following DOM with a pass-through in an onclick

 var tdButtonDOMCopy = $('#tD'+catSeq+'Button');

And this is the in-Jquery-created-button with reference to its next function:

 tdButtonDOM.replaceWith('<button id="buttonChange" onclick="approveFormEdit(\''+tdButtonDOMCopy+'\')"\n\
                          class="btn btn-primary">Sla wijziging op</button>');

I want to pass this entire DOM element [Object object] as parameter to its next function:

function approveFormEdit(tdButtonElement) {
   alert(tdButtonElement.html());
   .... - Omitted -

Now here is the funny thing:

In the onclick section the object tdButtonDOMCopy is seen as a DOM-object and I can use the .html() method on it.

Though, once the object reaches the function approveFormEdit the .html() method no longer works because it has lost the referrence DOM-object somehow.

在此处输入图片说明

What is going on here?

This is the fiddle with context

jsfiddle.net/1vdwv5r8

You are passing it in quotes thus its a string literal so the error is expected as .html() is a jQuery method.

You need to remove pass the tdButtonDOMCopy without quotes, then it will be treated as variable

tdButtonDOM.replaceWith('<button id="buttonChange" onclick="approveFormEdit(tdButtonDOMCopy)" class="btn btn-primary">Sla wijziging op</button>');

However, I would recommend you to pass the selector use data-* custom attribute which can be retrived in the event handler;

var tdButtonDOMCopy = '#tD' + catSeq + 'Button';
tdButtonDOM.replaceWith('<button id="buttonChange" data-target="' + tdButtonDOMCopy + '" class="btn btn-primary">Sla wijziging op</button>');

function approveFormEdit() {
    var targetSelector = $(this).data('target'); ;
    tdButtonElement = $(targetSelector);
}

$(document).on('click', '#buttonChange', approveFormEdit)

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