问题描述
我正在尝试将文本插入具有id的div元素中...我正在将window.open与jQuery一起使用,但这不起作用。有人知道如何执行此操作或替代方法吗?我将不胜感激任何信息。谢谢 这是我到目前为止所拥有的:
$("button").click(function() {
window.open('page2.html','_blank');
$("#imgdiv").html("hello");
})
解决方法
您的代码无法正常工作的原因是,您的代码会在单击按钮后立即且在打开新窗口之前完全执行。您将需要通过验证URL(window.location.href
)来检查打开的窗口。以下代码使用indexOf
确定网址是否包含page2.html
。如果找到,#imgdiv
将被更新。
$( document ).ready(function() {
if (window.location.href.indexOf("page2.html") > -1) {
$("#imgdiv").html("hello");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>