Window open()使用方法


open() 方法用於打開一個新的瀏覽器窗口或查找一個已命名的窗口

window.open(URL,name,specs,replace)

URL 可選。打開指定的頁面的URL。如果沒有指定URL,打開一個新的空白窗口
name 可選。指定target屬性或窗口的名稱
specs 可選。一個逗號分隔的項目列表 設置新的窗口得長,高,和位置等
replace Optional.Specifies規定了裝載到窗口的 URL 是在窗口的瀏覽歷史中創建一個新條目,還是替換瀏覽歷史中的當前條目。支持下面的值:
true - URL 替換瀏覽歷史中的當前條目。
false - URL 在瀏覽歷史中創建新的條目。

1.在頁面上,點擊打開新窗口時,則打開指定得窗口

<h1>window open 應用</h1>
<button onclick="f()">打開新窗口</button>
<script>
    function f() {
        window.open("https://www.cnblogs.com/","","width=600,height=300,top=100")
    }
</script>

2.點擊后,頁面跳轉到添加頁面,提交后,窗口關閉

在打開得新窗口中添加完數據后,窗口關閉,應該在另建一個新的頁面,在該頁面上寫上使窗口關閉得代碼,讓頁面跳轉到該頁面
def add(request):
    if request.method=='POST':
        title=request.POST.get("title")
        price = request.POST.get("price")
        models.Food.objects.create(price=price,title=title)
        return render(request,"pop.html")
    return render(request,"add.html")
pop.html
<script>
     window.close()
</script>

3.點擊后,頁面跳轉到添加頁面,提交后,窗口關閉,添加的數據顯示到頁面上

1.點擊添加按鈕時,為了將數據再返還給此頁面,應該識別是哪個按鈕進行的提交操作,因此對每個按鈕添加個類作識別
2.在給window open傳遞地址時,將這個類值作為參數傳遞過去,這個后端在處理完數據后,也能知道返還給誰
3.后端處理完,要跳轉到關閉窗口的頁面,將傳遞的數據傳到這個頁面,這個頁面再將數據給顯示頁面。
用window.opener接收
4.再顯示頁面找到對應的標簽,將值賦給該標簽
add.html
<form action="" method="post">
    {% csrf_token %}
    <p>
        <label for="title">食物名稱</label>
         <input type="text" id="title" name="title">
    </p>
   <p>
         <label for="price">食物價格</label>
        <input type="text" id="price" name="price">
   </p>
    <p><input type="submit" value="提交"></p>
</form>
index.html
<h1>window open 應用</h1>
<button onclick="f(this)" class="show1">添加數據1</button>
<p id="show1"></p>
<hr>
<button onclick="f(this)" class="show2">添加數據2</button>
<p id="show2"></p>
<script>
    function f(self) {
        為路徑添加參數,self.className獲得該標簽類的值
        url="/add/?pop="+self.className;
        window.open(url,"","width=600,height=300,top=100")
    };
    function bar(arg,pop){
        var ele=document.getElementById(pop);
        ele.innerText=arg;
    }
</script>
pop.html 關閉窗口頁面
 
        
<script>
    window.opener.bar("{{ food.title }}","{{ pop }}");
    window.close()
</script>
def index(request):
    return render(request,"index.html")
def add(request):
    if request.method=='POST':
        title=request.POST.get("title")
        price = request.POST.get("price")
        ##只要路徑上有參數,POST請求中也可以使用GET
        pop=request.GET.get("pop")
        food=models.Food.objects.create(price=price,title=title)
        return render(request,"pop.html",{"food":food,"pop":pop})
    return render(request,"add.html")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM