简体   繁体   English

如何从jQuery函数生成动态HTML时处理输入参数

[英]How to handle input parameters while generating dynamic html from jquery function

I am using below function to generate dynamic HTML. 我正在使用下面的函数来生成动态HTML。

function (content) {
    $('#divMessage').append('<span>'+ content+ '</span>');
}

Here I am appending content in div with id divMessage . 在这里,我将id为divMessage的内容附加到div中。

Here input parameter content can be any text passed to this function. 在这里,输入参数的内容可以是传递给此函数的任何文本。

I am facing problem when I pass data containing html elements as it distorts html. 我传递包含html元素的数据时会遇到问题,因为它会使html变形。 I am not aable to paste it here as its get dostorted here in stack overflow editor as well. 我无法将其粘贴到此处,因为它也在堆栈溢出编辑器中被添加到此处。

How can I resolve this issue, TIA. TIA,我该如何解决这个问题。

在此处输入图片说明

It should append what is being passed, don't want to convert html tags to html, if html tag with data is passed then html tag with data should be the ouput. 它应该附加正在传递的内容,不要将html标签转换为html,如果传递了带有数据的html标签,则应该是带有数据的html标签。

To resolve this you need to only paser the content text to HTML 要解决此问题,您只需将内容文本粘贴到HTML

Just do this 做这个

    content= $.parseHTML(content);
$('#divMessage').append('<span>'+ content+ '</span>');

Hope it will help! 希望对您有所帮助!

You can pass html value like this. 您可以像这样传递html值。

 function AddContent(content) { $('#divMessage').append('<span>'+ content+ '</span>'); } $("#divAppendMessage").on("click", function() { //$('#divMessage').html(''); // If you want to clear div before append var html=''; html+='<h1>My new message</h1>';// You can add mark up like this.Be sure for closing tag. AddContent('<h1>My new message</h1>');// Pass html without generate markup as OP say on comment. }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='divMessage'> </div> <button id='divAppendMessage'>Add Message</button> 

May be this fiddle solve your problem. 可能是这个小提琴解决了您的问题。 Before get input from user convert it and reset it when bind. 在获得用户输入之前,先将其转换并在绑定时重置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM