使用jquery .html()

时间:2016-05-13 23:54:40

标签: javascript jquery html

如何使用Jquery html获取元素本身的html。在下面的代码中,我想使用JQuery作为shwon获取div中的输入元素

<div id="content">content div</div>
<input type='text' id="scheduledDate" class="datetime" />

$(function() {

   console.log($('#scheduledDate').html('dsadasdasd'));
    $('#content').html($('#scheduledDate').html());
});

修改

我可以将$(&#34;#scheduledDate&#34;)作为字符串来表示输入框的真实html代码,因为我的最终要求是我想将它传递给其他一些SubView(我正在使用backboneJS)并最终在尘埃文件中使用该HTML代码。        我最初的要求是将输入字段作为字符串,以便我可以将其传递给其他函数。我知道,如果我将它保存在DIV或其他容器中,我可以使用JQuery的.html方法获取html。我不想为此目的使用其他一些东西。我只是想使用它的id来获取输入框本身的html内容。

4 个答案:

答案 0 :(得分:1)

如果要将输入元素移动到div中,请尝试以下操作:

$('#content').append($('#scheduledDate'));

如果要将输入元素复制到div中,请尝试以下操作:

$('#content').append($('#scheduledDate').clone());

注意:在move或copy元素之后,可能需要再次注册事件监听器。

答案 1 :(得分:0)

$(function() {

    var content = $('#content');
    var scheduledDate = $('#scheduledDate');

    content.empty();
    content.append(scheduledDate.clone());

});

正如原作者所说,他们明确地想要输入的html:

$(function() {

    var scheduledDate = $('#scheduledDate').clone();
    var temporaryElement = $('<div></div>');

    var scheduleDateAsString = temporaryElement.append(scheduledDate).html();

    // do what you want with the html such as log it
    console.log(scheduleDateAsString);
    // or store it back into #content
    $('#content').empty().append(scheduleDateAsString);

});

我是如何实现这一点的。请参阅下面的工作示例: https://jsfiddle.net/wzy168xy/2/

答案 2 :(得分:0)

简单或纯JavaScript方法,可以做得更好......

scheduledDate.outerHTML //HTML5

或通过

致电
document.getElementById("scheduledDate").outerHTML //HTML4.01 -FF.

应该/返回相同的内容,例如:

>>  '<input id="scheduledDate" type="text" value="" calss="datetime">'

如果这是你要求的 fiddle

p.s:“calss”是什么意思? : - )

答案 3 :(得分:-1)

这可以通过以下方式完成:

1.输入框移动到div,div内容与添加的输入

一起保留
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").append($inputBox);
});

2. div被替换为输入框的副本(如nnn指出的那样)

$(document).ready(function() {

    var $inputBox = $("#scheduledDate");
    var $clonedInputBox = $("#scheduledDate").clone();
    $("#content").html($clonedInputBox);

    });
  1. Div被原始输入框替换

    $(document).ready(function(){

    var $inputBox = $("#scheduledDate");
    $("#content").html($inputBox);
    
    });
    
  2. https://jsfiddle.net/atg5m6ym/4485/

    编辑1: 要将输入html作为div中的字符串本身使用此

    $("#scheduledDate").prop('outerHTML')
    

    这将输入对象html作为字符串 检查这个js小提琴并告诉你这是否是你需要的

    https://jsfiddle.net/atg5m6ym/4496/