简体   繁体   中英

Converting escaped text to html in javascript?

I used $.get and received data like

'<option value=\"US-ID\" >Idaho<\/option>\n  <option value=\"US-IL\" >Illinois<\/option>\n  <option value=\"US-IN\" >Indiana<\/option>\n  <option value=\"US-KS\" >Kansas<\/option>\n'

I want to use $(...).html(html_data) how do I make the data I get into html data that I can use?

what I'm getting when $(...).html(data)

http://jsfiddle.net/9WeUv/

Don't know if this matters, but console.log(data) :

'...data...'

whereas console.log('regular_string') :

regular_string // no quotes

What's wrong with:

var html_data = '<option value=\"US-ID\" >Idaho<\/option>\n  <option value=\"US-IL\" >Illinois<\/option>\n  <option value=\"US-IN\" >Indiana<\/option>\n  <option value=\"US-KS\" >Kansas<\/option>\n';

$('#select_element_id').html(html_data);

http://jsfiddle.net/45CYX/

After your edit:

Sorry, isn't the string you've received the one you wrote on top? In your jsFiddle you do not have any JS code, just some text in a select tag - which is not what you are saying in the question.

Assuming you grabbed the html from an ajax call and want to add it to the body.

$newSelect = $("<select></select>").html(html_data);
$(document.body).append($newSelect);

http://api.jquery.com/jQuery/#jQuery2 - Creates DOM elements on the fly from the provided string of raw HTML.

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