how to get outerHTML with jquery in order to have

2019-08-02 21:05发布

I found a response in a jquery forum and they made a function to do this but the result is not the same. Here is an example that I created for an image button:

var buttonField = $('<input type="image" />');
    buttonField.attr('id', 'butonFshi' + lastsel);
    buttonField.val('Fshi');
    buttonField.attr('src', 'images/square-icon.png');
    if (disabled)
        buttonField.attr("disabled", "disabled");
    buttonField.val('Fshi');
    if (onblur !== undefined)
        buttonField.focusout(function () { onblur(); });
    buttonField.mouseover(function () { ndryshoImazhin(1, lastsel.toString()); });
    buttonField.mouseout(function () { ndryshoImazhin(0, lastsel.toString()); });
    buttonField.click(function () { fshiClicked(lastsel.toString()); });

And I have this situation:

 buttonField[0].outerHTML = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`

instead the outer function I found gives buttonField.outer() = <INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image>

The function is:

$.fn.outer = function(val){
    if(val){
        $(val).insertBefore(this);
        $(this).remove();
    }
    else{ return $("<div>").append($(this).clone()).html(); }
}

so like this I loose the handlers that I inserted. Is there anyway to get the outerHTML with jquery in order to have it cross-browser without loosing the handlers ?!

4条回答
小情绪 Triste *
2楼-- · 2019-08-02 21:20

This should work fine:

var outer = buttonField.parent().html();
查看更多
够拽才男人
3楼-- · 2019-08-02 21:27

You don't need convert it to text first (which is what disconnects it from the handlers, only DOM nodes and other specific JavaScript objects can have events). Just insert the newly created/modified node directly, e.g.

$('#old-button').after(buttonField).remove();`

after returns the previous jQuery collection so the remove gets rid of the existing element, not the new one.

查看更多
老娘就宠你
4楼-- · 2019-08-02 21:34

Check out the jQuery plugin from https://github.com/darlesson/jquery-outerhtml. With this jQuery plugin you can get the outerHTML from the first matched element, replace a set of elements and manipulate the result in a callback function.

Consider the following HTML:

<span>My example</span>

Consider the following call:

var span = $("span").outerHTML();

The variable span is equal <span>My example</span>.

In the link above you can find more example in how to use .outerHTML() plug-in.

查看更多
5楼-- · 2019-08-02 21:43

Try this one:

var html_text = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`
buttonField[0].html(html_text);

:)

查看更多
登录 后发表回答