问题情境:
在调用浏览器打印功能方法window.print()后,页面出现错乱进而使用window.document.body.innerHTML替换页面进行解决从而出现事件丢失问题。
代码片段:
let bdhtml = window.document.body.innerHTML;
window.print(); //调用浏览器的打印功能
window.document.body.innerHTML = bdhtml; // 最后还原页面
问题分析:
MDN 链接有这句,会移除元素的所有子元素
Setting the value of
innerHTML
removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string
htmlString
解决方法:
1.利用事件代理,全部委托给document,然后通过targe确定事件源
2.统一管理监听事件注销
3.使用location.reload()当前页面刷新
最终代码:
let bdhtml = window.document.body.innerHTML;
window.print(); //调用浏览器的打印功能打印指定区域
window.document.body.innerHTML = bdhtml; // 最后还原页面
location.reload(); // 刷新页面
最近再写一个项目,用到了
innerHTML
,但是呢,发现调用
innerHTML
之后,onclick失效了,这也是在意料之中的,因为
innerHTML
是以文本形式插入的button,所以无法识别onclick
事件
,所我们只有另找出路了,我们不能直接实现,但是可以间接实现,下面就举个例子:
例子一:该例子是无法实现的onclick的
function insCell(th)
用
innerHTML
取出一段内容后再
innerHTML
回去,那么原来动态绑定的
事件
就会
丢失
,如:
html
: 代码如下: <
body
><div id=’d1′>点击</div></
body
> script: 代码如下:
document
.getElementById(‘d1’).onclick=function(){alert(1)}; var
html
=
document
.
body
[removed];
document
.
body
[removed]=
html
; 这段代码执行后点击d1是没有任何反应的。
解决
方法: 把onclick绑定到父元素,利用冒泡原理,判断当前元素是否为d1,若
function doPrint() {
bd
html
=
window
.
document
.
body
.
innerHTML
;
sprnstr = "<!--startprint-->";
eprnstr = "<!--endprint-->";
<div>ccccccccccccccccccc</div>
<div id="toPrint" style="color:red">ddddddddddddddddddddd</div>
<formname=form1 >
<input type=buttononclick="
document
.
body
.
innerHTML
='loading....<input type =text>'";>
</form>
</
body
>
</htm...
写一个淘宝手机链接转换为电脑链接的完整
html
代码,首先获取用户输入的淘宝手机链接,并使用 URL 对象解析出链接中的产品 ID。接着,将获取到的产品 ID 拼接到 https://detail.tmall.com/item.htm?id= 后面,得到电脑链接。最后,使用
innerHTML
属性将电脑链接显示在
页面
上,并提供一个新窗口打开链接的超链接。
function convert() {
var inputUrl =
document
.getElementById("inputUrl").value;
var url = new URL(inputUrl);
var productId = url.searchParams.get("id");
var outputUrl = "https://detail.tmall.com/item.htm?id=" + productId;
document
.getElementById("outputUrl").
innerHTML
= outputUrl;
window
.productUrl = outputUrl;
function openUrl() {
window
.open(
window
.productUrl);
</script>
</
body
>
</
html
>
在这个
HTML
代码中,我们首先创建了一个表单,让用户输入淘宝手机链接。然后,我们使用 `URL` 对象解析出链接中的产品 ID,拼接成电脑链接,并将电脑链接显示在
页面
上。同时,我们创建了一个新窗口打开链接的超链接,当用户点击这个超链接时,会在新窗口打开电脑链接。
需要注意的是,我们使用了 `
window
.productUrl` 变量来存储电脑链接,在 `openUrl` 函数中使用这个变量来打开链接。这是因为在
JavaScript
中,如果我们在一个函数内部声明一个变量,那么这个变量只在函数内部有效。为了在两个函数之间共享数据,我们需要将这个变量声明在全局作用域中。