html:<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>test</title> <link rel="stylesheet" href="./showbox.css"></head><body> <script src="./jQuery-1.12.4.js"></script> <script src="./showbox.js"></script> <script> $(function(){ var box = new ShowBox(); box.push('hello world'); }); </script></body></html>js:(function(){ function ShowBox(){}; ShowBox.prototype = { push:function(content){ var layer = '<div class="showbox_layer"></div>'; if(content){ $('html,body').html(layer); } } } window.ShowBox = ShowBox;}());页面中的jquery正常引入。问题:运行页面后,F12调出控制台。head部分没有内容,同时页面样式也未能生效。(已确定引入样式)
2 回答
一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
为什么要使用$('html,body')?$('html,body')选中的是两个元素,也就是html元素和body元素,.html方法是把元素的内容用.html的参数完全覆盖。
也就是首先html元素的内容完全被<div class="showbox_layer"></div>替换,可能是给html添加元素的时候,因为div不是html的有效元素,所以会生成一个空的head标签,一个空的body标签,然后把<div class="showbox_layer"></div>放入body里;
然后是body元素的内容完全被<div class="showbox_layer"></div>替换,因为替换前body就只有<div class="showbox_layer"></div>,所以替换后和替换前展示的内容是一样的。
所以就导致了截图中的效果,你没有发现不仅head空了,body的script标签也没有了吗。
所以首先把$('html,body')修改为$('body'),然后把.html方法替换为.prepend或者.append方法:
$('body').prepend(layer);是否用.prepend方法替换.html方法要看你的需求,如果你的需求就是完全替换,那么用.html方法就行,如果是添加的话,还是换为.prepend或者.append比较好。
添加回答
举报
0/150
提交
取消
