我在任何文章上都找不到任何解決方案,所以我在這里問。我想制作將用戶重定向到特定網址的按鈕。我已經這樣做了:
<button onclick="location.href='create_recipe/'" type="button" >Create new Recipe</button>
但我不想傳遞整個鏈接,{% url 'some_view' %}但我不知道我應該怎么做。甚至有可能做到這一點嗎?
它必須是<button>,
編輯:
就像是:
<button type="button" ><a href="{% url 'index' %}">Create new Recipe</a></button>
也不起作用
uj5u.com熱心網友回復:
您可以通過將其添加到按鈕來做到這一點:
onclick="goToSomeView()"
然后將其添加到 html 檔案的腳本標記中:
<script type="text/javascript">
function goToSomeView(){
document.location.href = "{% url 'some_view' %}"
}
</script>
uj5u.com熱心網友回復:
index是您存在views.py檔案的函式。
from django.urls import path
from . import views
path('',views.index, name='index'),
HTML:
<a class="btn btn-outline-secondary" href="{% url 'index' %}">Create new Recipe</a>
uj5u.com熱心網友回復:
正如我看到你已經在使用引導程式,所以最簡單的方法是使用帶有屬性的a元素。type="button"
<a href="{% url 'index' %}" type="button" class="btn btn-outline-secondary">Create new recipe</a>
下面你可以看到結果是一樣的,但是button你需要系結onclick函式。在這種情況下,我指向@nigel239 的答案。
function goToSomeView(){
document.location.href = "{% url 'index' %}"
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<p class="lead">Using 'a' element</p>
<a href="{% url 'index' %}" type="button" class="btn btn-outline-secondary">Create new recipe</a>
<p class="lead mt-3">Using button</p>
<button onclick="goToSomeView()" class="btn btn-outline-secondary">Create new recipe</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/505691.html
