有没有办法做到这一点?我的 ajax 设置了一个 javascript 变量,但是当我尝试使用 document.write 显示它时,它覆盖了 html 元素。可以这样做以便我可以使用 javascript 变量而不是掩盖 html 元素吗?提前致谢。
<html>
<head>
<title>Log In</title>
<!-- script tag for ajax jquery -->
<link href='style.css' type="text/css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
//Get Data ajax function
$.post(
'getData.php',
{
},
function(response)
{
$('#name').html($('#1' , response).html());
$('#sname').html($('#2' , response).html());
var x = $('#1' , response).html();
document.write(x);
})
return false;
})
</script>
</head>
<body>
<div id="name"></div>
<div id="sname"></div>
this is text that get covered up, as well as any other html elements
</body>
</html>
最佳答案
document.write
主要用于在 页面加载期间。响应事件时,通过createElement
、appendChild
等函数修改DOM;或类似 innerHTML
的属性。
例如,如果您想将 x
的内容作为标记附加到 div
中,而不是
document.write(x);
你会这样做:
var div = document.createElement('div');
div.innerHTML = x;
document.body.appendChild(div);
如果您想找到 DOM 中已有的元素并对其进行修改,您可以使用 document.getElementById
(如果它有 ID)或 document.getElementsByTagName
获取具有给定标签的元素列表(都是 DOM2 的一部分),或者(在大多数但不是所有当前浏览器上),querySelector
和 querySelectorAll
来自 selectors API .
更多阅读:
关于javascript - 设置 javascript 变量的 Ajax 响应覆盖了任何 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9344534/