Hướng dẫn how do i return a javascript string to html? - làm cách nào để trả lại chuỗi javascript thành html?

Dưới đây là một vài ví dụ về cách bạn có thể chuyển đổi chuỗi HTML thành DOM

  1. Nếu bạn đang mong đợi chuỗi HTML sẽ bắt đầu với bất kỳ nội dung nào hợp lệ bên trong

    function html2dom(str) {
        return (new DOMParser).parseFromString(str, 'text/html');
    }
    
    1

    function str2dom(str) {
        var d = document.createElement('div'),
            df = document.createDocumentFragment();
        d.innerHTML = str;
        while (d.childNodes.length)
            df.appendChild(d.childNodes[0]);
        return df;
    }
    
  2. Nếu bạn đang mong đợi chuỗi HTML bắt đầu với

    function html2dom(str) {
        return (new DOMParser).parseFromString(str, 'text/html');
    }
    
    2,
    function html2dom(str) {
        return (new DOMParser).parseFromString(str, 'text/html');
    }
    
    3

    function html2dom(str) {
        return (new DOMParser).parseFromString(str, 'text/html');
    }
    

Nếu bạn bắt đầu với

function html2dom(str) {
    return (new DOMParser).parseFromString(str, 'text/html');
}
4, bạn có thể cần sửa đổi một trong các phương thức trên. Nếu HTML của bạn không hợp lệ, bạn có thể gặp lỗi
If your HTML is invalid you may get an Error


Sau khi sử dụng một trong các phương thức trên, bạn có thể nối thêm những gì bạn muốn vào một nút bạn chọn với

function html2dom(str) {
    return (new DOMParser).parseFromString(str, 'text/html');
}
5


Nếu bạn đang hỏi làm thế nào để tạo một nút thay vì một chuỗi, hãy sử dụng các phương thức DOM, chẳng hạn như

function html2dom(str) {
    return (new DOMParser).parseFromString(str, 'text/html');
}
6

function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​

JavaScript trở lại

Các câu lệnh trước Javascript tiếp theo ❯ Previous JavaScript Statements Next


Ví dụ

Trả về giá trị của PI:

function myFunction () {& nbsp; & nbsp; return math.pi;}
  return Math.PI;
}

Hãy tự mình thử »

Trả lại "Xin chào John":

document.getEuityById ("demo"). innerHtml = myFunction ("john");

hàm myfunction (tên) {& nbsp; Trả lại "Xin chào" + Tên; }
  return "Hello " + name;
}

Hãy tự mình thử »

Trả lại "Xin chào John":


document.getEuityById ("demo"). innerHtml = myFunction ("john");

hàm myfunction (tên) {& nbsp; Trả lại "Xin chào" + Tên; }

Thêm ví dụ dưới đây.


Định nghĩa và cách sử dụng

Câu lệnh

function html2dom(str) {
    return (new DOMParser).parseFromString(str, 'text/html');
}
7 dừng việc thực thi hàm và trả về một giá trị.

Đọc hướng dẫn JavaScript của chúng tôi để tìm hiểu tất cả những gì bạn cần biết về các chức năng. Bắt đầu với chương giới thiệu về các hàm JavaScript và phạm vi JavaScript. Để biết thêm thông tin chi tiết, hãy xem phần chức năng của chúng tôi về các định nghĩa chức năng, tham số, lệnh gọi và đóng.

Cú pháp Giá trị trả lại;
Thông sốTham số
The value to be returned.
If omitted, it returns
function html2dom(str) {
    return (new DOMParser).parseFromString(str, 'text/html');
}
8


Sự mô tả

giá trị

Tùy chọn. Giá trị sẽ được trả về. Nếu bị bỏ qua, nó sẽ trả về

function html2dom(str) {
    return (new DOMParser).parseFromString(str, 'text/html');
}
8
var x = myFunction(4, 3);

Nhiều ví dụ hơn
  // Return the product of a and b
  return a * b;
}

Hãy tự mình thử »


Trả lại "Xin chào John":

document.getEuityById ("demo"). innerHtml = myFunction ("john");

hàm myfunction (tên) {& nbsp; Trả lại "Xin chào" + Tên; }

Thêm ví dụ dưới đây.

Định nghĩa và cách sử dụng

Câu lệnh

function html2dom(str) {
    return (new DOMParser).parseFromString(str, 'text/html');
}
7 dừng việc thực thi hàm và trả về một giá trị.

Đọc hướng dẫn JavaScript của chúng tôi để tìm hiểu tất cả những gì bạn cần biết về các chức năng. Bắt đầu với chương giới thiệu về các hàm JavaScript và phạm vi JavaScript. Để biết thêm thông tin chi tiết, hãy xem phần chức năng của chúng tôi về các định nghĩa chức năng, tham số, lệnh gọi và đóng.

Cú pháp


Giá trị trả lại;

Thông số

Tham số

Sự mô tảgiá trịTùy chọn. Giá trị sẽ được trả về. Nếu bị bỏ qua, nó sẽ trả về
function html2dom(str) {
    return (new DOMParser).parseFromString(str, 'text/html');
}
8
Nhiều ví dụ hơnTính toán sản phẩm của hai số và trả về kết quả: // gọi hàm và lưu giá trị trả về trong x: var x = myfunction (4, 3);
hàm myFunction (a, b) {& nbsp; & nbsp; // trả về sản phẩm của a và b & nbsp; & nbsp; return a * b; } hàm myFunction (a, b) {& nbsp; & nbsp; // trả về sản phẩm của a và b & nbsp; & nbsp; return a * b; } hàm myFunction (a, b) {& nbsp; & nbsp; // trả về sản phẩm của a và b & nbsp; & nbsp; return a * b; } hàm myFunction (a, b) {& nbsp; & nbsp; // trả về sản phẩm của a và b & nbsp; & nbsp; return a * b; } hàm myFunction (a, b) {& nbsp; & nbsp; // trả về sản phẩm của a và b & nbsp; & nbsp; return a * b; } hàm myFunction (a, b) {& nbsp; & nbsp; // trả về sản phẩm của a và b & nbsp; & nbsp; return a * b; }

Các câu lệnh trước Javascript tiếp theo ❯ Previous JavaScript Statements Next


Hôm qua, tôi đã viết về rạn san hô, sự thay thế nhẹ của tôi cho Vue và React. Trong vài ngày tới, tôi muốn xem cách các phần khác nhau của nó hoạt động dưới thời trang.

Hôm nay, chúng tôi sẽ xem xét cách lấy một chuỗi HTML và chuyển đổi nó thành đánh dấu thực tế.

Tại sao bạn cần điều này

Nếu bạn muốn tiêm một chuỗi vào DOM, bạn có thể làm điều đó khá đơn giản với

function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
0.

app.innerHTML = '

Hello, world!

'
;

Nhưng rạn san hô không chỉ đẩy đánh dấu vào một yếu tố. Nó so sánh đánh dấu hiện có trong một yếu tố với cách nhìn và chỉ cập nhật những thứ cần thay đổi.

Ví dụ: nếu nội dung hiện có bên trong

function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
1 là:

Rạn san hô sẽ chỉ cập nhật văn bản bên trong

function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
2 thay vì tạo một phần tử hoàn toàn mới.

Để nó hoạt động, chúng ta cần chuyển đổi chuỗi HTML thành các phần tử HTML thực tế có thể đi qua, ánh xạ và phân tích.

Tạo phương pháp trợ giúp

Đầu tiên, hãy để tạo ra một hàm trợ giúp sẽ chấp nhận một chuỗi và trả về HTML.

/**
 * Convert a template string into HTML DOM nodes
 * @param  {String} str The template string
 * @return {Node}       The template HTML
 */
var stringToHTML = function (str) {
	// Code goes here...
};

Cách tiếp cận đơn giản

Cách đơn giản nhất để làm điều này là tạo một phần tử, chèn chuỗi vào với

function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
0, sau đó trả về phần tử.

/**
 * Convert a template string into HTML DOM nodes
 * @param  {String} str The template string
 * @return {Node}       The template HTML
 */
var stringToHTML = function (str) {
	var dom = document.createElement('div');
	dom.innerHTML = str;
	return dom;
};

Cách tiếp cận này là hoàn hảo, mặc dù.

Mặc dù yếu tố này được tách ra, đó là, không thực sự trong DOM hiện tại, trình duyệt vẫn sẽ làm những việc như tải xuống các tệp hình ảnh.

Điều này sẽ kích hoạt một tệp hình ảnh để tải xuống, mặc dù đánh dấu không được hiển thị ở bất cứ đâu.

stringToHTML('
Hướng dẫn how do i return a javascript string to html? - làm cách nào để trả lại chuỗi javascript thành html?
'
);

Một cách tốt hơn

Sau khi thực hiện một loạt các nghiên cứu, tôi đã phát hiện ra một phương pháp trình duyệt gốc để tránh vấn đề này:

function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
4. Đối tượng
function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
4 tạo một tài liệu DOM mới từ một chuỗi.

Để sử dụng nó, bạn khởi tạo một thể hiện mới. Sau đó, bạn sử dụng phương thức

function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
6 để chuyển đổi chuỗi của mình thành phần tử
function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
7 mới. Phương thức chấp nhận chuỗi khi nó đối số đầu tiên. Đặt đối số thứ hai thành
function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
8.

Bởi vì nó có nghĩa đen là một yếu tố

function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
7 mới, chúng tôi sẽ trả lại
app.innerHTML = '

Hello, world!

'
;
0.

/**
 * Convert a template string into HTML DOM nodes
 * @param  {String} str The template string
 * @return {Node}       The template HTML
 */
var stringToHTML = function (str) {
	var parser = new DOMParser();
	var doc = parser.parseFromString(str, 'text/html');
	return doc.body;
};

Bây giờ chúng ta có thể làm điều này, và không có tải xuống sẽ được kích hoạt.

stringToHTML('
Hướng dẫn how do i return a javascript string to html? - làm cách nào để trả lại chuỗi javascript thành html?
'
);

Kết hợp hai cách tiếp cận

Phương pháp

function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
4 là tuyệt vời, nhưng phương pháp
function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
6 dừng ở IE10.

Tôi thích kết hợp hai cách tiếp cận, sử dụng

function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
4 khi nó được hỗ trợ và rơi trở lại để tạo ra một yếu tố và sử dụng
function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
0 khi nó không.

Để kiểm tra hỗ trợ, chúng tôi sẽ chỉ định một iife cho biến

app.innerHTML = '

Hello, world!

'
;
5.

Bên trong iife, trước tiên chúng tôi sẽ kiểm tra xem

app.innerHTML = '

Hello, world!

'
;
6 có tồn tại trong
app.innerHTML = '

Hello, world!

'
;
7 không. Nếu không, chúng tôi sẽ trả lại
app.innerHTML = '

Hello, world!

'
;
8. Tiếp theo, chúng tôi sẽ cố gắng sử dụng
function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
6 để tạo
function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
7. Nếu nó thất bại, chúng tôi sẽ trả lại
app.innerHTML = '

Hello, world!

'
;
8. Nếu không, chúng tôi sẽ trở lại
/**
 * Convert a template string into HTML DOM nodes
 * @param  {String} str The template string
 * @return {Node}       The template HTML
 */
var stringToHTML = function (str) {
	// Code goes here...
};
2.

var support = (function () {
	if (!window.DOMParser) return false;
	var parser = new DOMParser();
	try {
		parser.parseFromString('x', 'text/html');
	} catch(err) {
		return false;
	}
	return true;
})();

Bên trong phương pháp

/**
 * Convert a template string into HTML DOM nodes
 * @param  {String} str The template string
 * @return {Node}       The template HTML
 */
var stringToHTML = function (str) {
	// Code goes here...
};
3 của chúng tôi, chúng tôi sẽ sử dụng
function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
4 một cách có điều kiện khi nó hỗ trợ và
function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement ​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement hello world​
0 khi nó không.

function html2dom(str) {
    return (new DOMParser).parseFromString(str, 'text/html');
}
0

Ở đây, một bản demo trên Codepen để bạn chơi xung quanh.

Ngày mai, chúng tôi sẽ xem xét cách tạo bản đồ các nút dom mà chúng tôi có thể sử dụng cho Dom Diffing.

Bạn có thể trả lại một chuỗi JavaScript không?

Để trả về một chuỗi từ hàm JavaScript, hãy sử dụng câu lệnh trả về trong JavaScript.use the return statement in JavaScript.

Trả về {} trong javascript là gì?

Câu lệnh trả về dừng việc thực thi hàm và trả về một giá trị. Đọc hướng dẫn JavaScript của chúng tôi để tìm hiểu tất cả những gì bạn cần biết về các chức năng.stops the execution of a function and returns a value. Read our JavaScript Tutorial to learn all you need to know about functions.