簡體   English   中英

如何通過使用href更改網址來調用或顯示div?

[英]how to call or display a div by changing url using href?

我正在嘗試顯示當前隱藏在主體標簽內的div。通過使用錨標簽屬性href。

<a id="ai" href="managevendors" class="tablink" onclick="openCity()">Manage Vendors
</a>
<div class="w3-container city" style="display: none;" id="managevendors">
<h1>hi,how are you</h1>
</div>

當我單擊此錨標記時,我的網址肯定會更改。根據網址,我想顯示一個div。 我的js代碼...

function openCity() {
    if (window.location.hash == "managevendors") {
    $("#managevendors").show();
    }
}

我不知道為什么這是行不通的。

<a id="ai" href="#managevendors" class="tablink" onclick="openCity('managevendors')">Manage Vendors
</a>

和js代碼.....

function openCity()
{
  if (window.location.hash == "#managevendors") {
    $("#managevendors").show();
    }
}

但是我不想唱歌,我該怎么解決。幫助我先體驗一下brothers.thanks。

如果希望導航正常運行,則必須使用哈希。 完成后,您無需檢查它,只需顯示以下部分:

 $("#ai").on("click", openCity); function openCity() { // The only reason this code is running is because the link was clicked. // No need to test for it. $("#managevendors").show(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- You have to include the hash in the href for navigation to work --> <a id="ai" href="#managevendors" class="tablink">Manage Vendors </a> <div class="w3-container city" style="display: none;" id="managevendors"> <h1>hi,how are you</h1> </div> 

我認為這里的問題是,當您應該使用按鈕時,您正在使用錨標記。 第一種方法不起作用的原因是由於單擊鏈接時頁面刷新。

嘗試將您的<a>更改為<button>

據我了解,您很可能需要帶哈希的href="#xyz" 這將使客戶端邏輯保持活動狀態,而無需嘗試解析url,而繞開服務器則一無所獲。 如果要捕獲該部分,請將其保留在本地。

我建議從HTML中刪除onclick處理程序。 要捕獲鏈接,您可以使用jQuery使HTML保持“干凈”。 如果出於某種奇怪的原因,您一定可以引用onclick="openCity(this)" ,那么您單擊的元素將直接傳遞給openCity

// vanilla
function openCity(element){
    var href = element.getAttribute('href'), // expecting a hash here
        id = href.substr(1), // remove the hash
        target = document.getElementById(id);

    target.className += " active";
    return false;
}

正如Scott建議使用jQuery:

//$('.tablink').on('click', openCity);
$('.tablink[href^="#"]').on('click', openCity);

然后,可以通過單擊所單擊元素的href來使函數動態化:

function openCity(ev){
    var el = $(ev.currentTarget),
        id = el.prop('href'), // expecting a hash here
        target = $(id);

    // since you're providing both with and without hash, the default behaviour is to follow the link, unless referenced with a hash
    ev.preventDefault();
    target.addClass('active');
}

如果在頁面上未找到該ID,則該消息將靜默無效。


現在,如果您要使用url作為入口點,請注意,這只會在加載事件=>共享鏈接時發生,並且有人單擊它(附加#xyz )或直接在地址欄中鍵入。

// 1. bind the event
$(window).load(function(){
    /*loadCity defined here or outside*/

    loadCity();
});

// 2. define what happens
function loadCity(){
    var id = window.location.hash, // expecting a hash here
        target = $(id);

    target.addClass('active');
}

由於此解決方案僅解決元素的狀態,因此可以在CSS中制作實際的顯示/隱藏部分。 非常簡單,就像您可能已經做過的那樣,還是使用動畫,過渡等。

.city { display: none; }
.city.active { display: block; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM