簡體   English   中英

document.getElementById(“ id”)與$(“#id”)

[英]document.getElementById(“id”) vs $(“#id”)

如果我通過文檔方法獲取x和y的值比確定好,但是如果我直接通過以下方法獲取x和y的值,那我就注釋掉了,然后得到錯誤,為什么會這樣呢?

 <!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
 <body>

    Select a fruit and click the button:
    <select id="mySelect">
      <option value="11">Apple</option>
      <option value="12">Orange</option>
      <option value="13">Pineapple</option>
      <option value="14">Banana</option>
    </select>

    <button type="button" onclick="myFunction()">Display index</button>

    <script>
    function myFunction() {

        var x = document.getElementById("mySelect").selectedIndex;
        var y = document.getElementById("mySelect").options;

        //var x = $("#mySelect").selectedIndex;
        //var y = $("#mySelect").options;


        alert("Index: " + y[x].index + " text is " + y[x].text + " and value is " +  y[x].value);
    }
    </script>

    </body>
    </html>

我得到錯誤,為什么會這樣

因為jQuery構造函數返回的對象沒有selectedIndexoptions屬性。


$('selector')根據DOM中的匹配項創建jQuery集合,而document.getElementId('selector')是對特定DOM元素的引用。

$('selector')包含對DOM元素的引用,但沒有DOM元素的屬性/方法,而是具有jQuery方法。

要使用DOM元素的屬性/方法,您可以使用方括號表示法從jQuery集合中“獲取” DOM元素,因為我們的jQuery集合是一個類似於數組的對象:

var x = $("#mySelect")[0].selectedIndex;
var y = $("#mySelect")[0].options;

或者,使用.get()

var x = $("#mySelect").get(0).selectedIndex;
var y = $("#mySelect").get(0).options;

或者,使用.prop()返回屬性值:

var x = $("#mySelect").prop('selectedIndex');
var y = $("#mySelect").prop('options');
  1. 對於document.getElementById(“ id”)與$(“#id”),請參閱此問題

  1.  var x = $("#mySelect").selectedIndex; var y = $("#mySelect").options; 

selectedIndexoptions undefined 您應該使用.text().val()


  1. 您的摘要的解決方案
     $('#btn').on('click', function() { // var x = document.getElementById("mySelect").selectedIndex; // var y = document.getElementById("mySelect").options; var x = $("#mySelect").val(); var y = $("#mySelect option:selected").text(); alert(x + " :: " + y); //alert("Index: " + y[x].index + " text is " + y[x].text + " and value is " + y[x].value); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> Select a fruit and click the button: <select id="mySelect"> <option value="11">Apple</option> <option value="12">Orange</option> <option value="13">Pineapple</option> <option value="14">Banana</option> </select> <button type="button" id="btn">Display index</button> 

小提琴

這些方法不存在於jQuery對象上,您可以console.log對象,並查看它們通過原型鏈繼承的內容。

從MDN:

摘要通過其ID返回對該元素的引用。

語法元素= document.getElementById(id); 哪里

element是對Element對象的引用;如果具有指定ID的元素不在文檔中,則為null。

要帶走的重要部分是對Element對象的引用。

在這里,您可以看到該對象可用的方法。

$("...")返回包含匹配元素的jQuery集合。 您不能直接訪問元素及其屬性,而是:

使用jQuery.get訪問器方法:

var x = $("#mySelect").get(0).selectedIndex;
var y = $("#mySelect").get(0).options;

取消引用元素:

var x = $("#mySelect")[0].selectedIndex;
var y = $("#mySelect")[0].options;

使用jQuery.prop

var x = $("#mySelect").prop("selectedIndex");
var y = $("#mySelect").prop("options");

說完這些,您可以將代碼更改為此:

var $selectedOption = $("#mySelect option:selected");
console.log(
    $selectedOption.index(),
    $selectedOption.text(),
    $selectedOption.val()
);

$()是一個jQuery對象構造函數,它將創建一個jQuery對象並將所選元素包裝在該對象內(仍然可以訪問所有DOM屬性,但不能直接訪問)。

getElementById()是一個本地javascript函數,可檢索具有其常規屬性的DOM元素。

通常,您不需要訪問jQuery Object中的DOM元素,因為您可以使用Object中的jQuery方法來操縱所選元素。 selects有點棘手,因為我看不到任何用於檢索選項列表的方法:

$('#select option'); //Selects all the options of the select
$('#select option').each(function(){
  //iterate all options of the select.
});
$('#select option:selected'); //Get the selected option.

會是等效的。 從那時起,您可以使用jQuery方法來操縱選項,例如:

$('#select option:selected').text(); //Option text
$('#select option:selected').val(); //Value of option

$(“#element”); 是一個類似於css-syntax的jQuery jQuery jQuery jQuery的DOM選擇器,它將所有匹配的結果收集在jQuery對象數組中,這些對象可以訪問整個jQuery函數,這些函數非常方便且易於使用。

而“ doucment.getElementById(” element);“是本機JavaScript函數。

JQuery是JavaScript的抽象層,具有更簡單的語法,開箱即用的強大工具/功能,還為您解決了瀏覽器兼容性問題。

簡而言之,它會在您不必理會的后台為您執行JavaScript。

您應該盡可能地習慣於對jQuery進行編碼,因為這會使您的生活變得更輕松,並且您不必為復雜而繁瑣的代碼而煩惱,而只產生了很小的效果,例如:用JavaScript原生編寫AJAX請求就像15與jQuery相比,更多行的代碼具有完全相同的效果。

某些功能完全相同的示例:

訪問元素

JavaScript:

alert(document.getElementById("element").name);

jQuery的:

alert($("#element").attr("name"));

循環元素

JavaScript:

var elements = document.getElementsByClassName("class");
for(var i = 0; i < elements.length; i++) {
    alert(var element = elements[i].name);
}

jQuery的:

$(".class").each(function() { 
    alert($(this).attr("name")); //This accesses the current element of each function as a full useable and handy object
});

這只是兩個示例,您可以看到它確實非常強大。 小代碼與普通JavaSCript中的大代碼完全相同。 當包含jQUery時,應始終嘗試充分利用其潛力。

-

您的JQuery樣式代碼:

<button id="btn_display_index" type="button">Display index</button>

<script type="text/javascript">
    //Will be executed any time the button with id "btn_display_index" is clicked!
    $("#btn_display_index").on("click", function() { 
        var currentOption = $("#mySelect option:selected");
        alert("Index: " + currentOption.attr("value") + " - Value: " + currentOption.html());
    });
</script>

暫無
暫無

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

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