簡體   English   中英

來自 jQuery $.ajax 調用的響應變量上的 javascript querySelector

[英]javascript querySelector on the response variable from a jQuery $.ajax call

我正在使用 Bootstrap 開發系統,但在打印某些表格時遇到了問題。 背景顏色未顯示在屏幕上。

我終於找到了解決html2canvas問題的方法

我可以簡單地在我的 html 上 querySelect 一個元素,html2canvas 會在畫布上“繪制”它,它會完全按照屏幕上的顯示進行打印。

為此,請使用以下代碼:

 html2canvas(document.querySelector("#capture")).then(canvas => { document.body.appendChild(canvas) });

我的問題是:我可以將 querySelector 與從 jQuery $.ajax 調用獲得的響應變量一起使用嗎?

我試圖以多種方式做到這一點,但從未奏效。 下面是一個例子:

 $.ajax({ url: 'url', type: 'POST', success: function (data) { html2canvas($(data).querySelector("#selector")).then(canvas => { let wnd = window.open("about:blank", ""); wnd.document.body.appendChild(canvas); }); } });

安迪關於我如何做到這一點的想法?

data可能是一個包含 HTML 的String 如果您想在 DOM 中使用它,您需要首先將其解析為 DOMNodes。 您可以通過使用DOMParser或 jQuery 的$.parseHTML將字符串作為另一個元素的 innerHTML 插入來做到這$.parseHTML 我在下面的代碼中使用了第一個。

 $.ajax({ url: 'url', type: 'POST', success: function (data) { var template = document.createElement('template');//you could elements other than <template> template.innerHTML = data;//parses the html string into DOM Nodes html2canvas(template.content.querySelector("#selector")).then(canvas => { let wnd = window.open("about:blank", ""); wnd.document.body.appendChild(canvas); }); } });

警告,我不知道 html2canvas,它可能需要將元素插入到頁面中......但我不這么認為。

編輯

作為檢索解析的 DOM 元素的示例:

 var htmlString = "<div id='new_div'><p id='new_p'>New Element</p></div>"; var template = document.createElement('template'); template.innerHTML = htmlString; //DOMNodes are parsed, but not attached to the document console.log('new DOMNodes are "floating" in memory, dont exist in document'); console.log(document.querySelector('#new_div')); console.log('should find the element in the template, which is not attached to the document'); console.log(template.content.querySelector('#new_div')); document.body.appendChild(template.content); console.log('attached nodes to the body. they should be findable on document now'); console.log(document.querySelector('#new_div')); //via jquery var newStuff = $.parseHTML(htmlString);//returns an array-like? var actualNewDiv = newStuff[0]; console.log('jquery parsed reference to the DOMNodes'); console.log(actualNewDiv);//could be passed to html2canvas without querySelector-ing console.log('since the root element IS the div, we cant query for it'); console.log(actualNewDiv.querySelector('#new_div')); console.log('we CAN querySelect the p, because it is a child'); console.log(actualNewDiv.querySelector('#new_p'));
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM