簡體   English   中英

如何通過javascript獲取標簽屬性而不使用id或類?

[英]How get tag attribute by javascript without using id or class?

我是javascript的新手。我正在嘗試下面的代碼來獲取href屬性。

<a href="facebook.com"  onclick="cheak()">Facebook</a>

        <script type="text/javascript">
        function cheak()
        {
            var a= document.getElementsByTagName("a").getAttribute('href');
            alert(a);
        }

</script>

我知道這是通過以下代碼工作的

document.getElementById("myid").getAttribute('href');  // if I use any id

但在標簽中我不想使用任何id或類。 我怎樣才能得到這個屬性不使用任何id或class在a標簽。

如果你在調用函數時傳入this函數。 它會將元素引用傳遞給您的函數,您可以使用它來獲取href的值:

<a href="facebook.com"  onclick="cheak(this)">Facebook</a>
<!-- Note -----------------------------^^^^            -->

<script type="text/javascript">
function cheak(a) {
     alert(a.href); // Gives you the fully-resolved URL
     alert(a.getAttribute("href")); // Gives you the content of the `href` attribute (not fully-resolved)
}
</script>

參數data是調用函數的完整標記

前言:在下面,我已經回答了在一般情況下如何在不使用idclass的情況下查找元素的問題。 但是如果你只想在你的cheak函數中使用該元素,那么Zain的答案是正確的方法(對代碼進行最小的更改;可以說正確的可能是現代事件連接)。


但在標簽中我不想使用任何id或類。 我怎樣才能得到這個屬性,而無需使用任何idclassa標簽。

你找到了元素選擇的瑞士軍刀: document.querySelector 有了它,您可以使用與該元素匹配的任何CSS選擇器

var href = document.querySelector("any selector here").getAttribute("href");

querySelector返回文檔中的第一個匹配項。 (還有querySelectorAll ,它返回一個列表。)它們在所有現代瀏覽器和IE8中都受支持。

由於您具有CSS選擇器的全部功能,因此您可以使用有關文檔中元素位置的任何內容來查找它。

對於特定示例,您的問題中的上下文太少,但例如,如果它是文檔中的 a

 var href = document.querySelector("a").getAttribute("href"); alert(href); 
 <a href="facebook.com" onclick="cheak()">Facebook</a> 

或者使用onclick

 var href = document.querySelector("a[onclick='cheak()']").getAttribute("href"); alert(href); 
 <a href="facebook.com" onclick="cheak()">Facebook</a> 

<a href="www.facebook.com"  onclick="cheak(event)">Facebook</a>

     <script type="text/javascript">
    function cheak(e)
    {
       e.preventDefault(); 
      //  var a= document.getElementsByTagName("a").getAttribute('href');
        alert(e.target);
    }

</script>

暫無
暫無

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

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