簡體   English   中英

如何使用 jQuery 按名稱選擇元素?

[英]How can I select an element by name with jQuery?

我有一個要擴展和隱藏的表列。 當我按class而不是按元素name選擇 jQuery 時,它似乎隱藏了<td>元素。

例如:

$(".bold").hide(); // Selecting by class works.
$("tcol1").hide(); // Selecting by name does not work.

請注意下面的 HTML。 第二列的所有行都具有相同的name 我如何使用name屬性創建這個集合?

<tr>
  <td>data1</td>
  <td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
  <td>data1</td>
  <td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
  <td>data1</td>
  <td name="tcol1" class="bold"> data2</td>
</tr>

您可以使用jQuery 屬性選擇器

$('td[name="tcol1"]')   // Matches exactly 'tcol1'
$('td[name^="tcol"]' )  // Matches those that begin with 'tcol'
$('td[name$="tcol"]' )  // Matches those that end with 'tcol'
$('td[name*="tcol"]' )  // Matches those that contain 'tcol'

可以使用[attribute_name=value]方式選擇任何屬性。 此處查看示例:

var value = $("[name='nameofobject']");

如果你有類似的東西:

<input type="checkbox" name="mycheckbox" value="11" checked="">
<input type="checkbox" name="mycheckbox" value="12">

你可以這樣閱讀:

jQuery("input[name='mycheckbox']").each(function() {
    console.log( this.value + ":" + this.checked );
});

片段:

 jQuery("input[name='mycheckbox']").each(function() { console.log( this.value + ":" + this.checked ); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="mycheckbox" value="11" checked=""> <input type="checkbox" name="mycheckbox" value="12">

您可以通過老式的方式按名稱獲取元素數組並將該數組傳遞給 jQuery。

 function toggleByName() { var arrChkBox = document.getElementsByName("chName"); $(arrChkBox).toggle(); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <title>sandBox</title> </head> <body> <input type="radio" name="chName"/><br /> <input type="radio" name="chName"/><br /> <input type="radio" name="chName"/><br /> <input type="radio" name="chName"/><br /> <input type="button" onclick="toggleByName();" value="toggle"/> </body> </html>

注意:您唯一有理由使用“名稱”屬性的應該是復選框或無線電輸入。

或者您可以向元素添加另一個類以供選擇。(這就是我會做的)

 function toggleByClass(bolShow) { if (bolShow) { $(".rowToToggle").show(); } else { $(".rowToToggle").hide(); } }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <title>sandBox</title> </head> <body> <table> <tr> <td>data1</td> <td class="bold rowToToggle">data2</td> </tr> <tr> <td>data1</td> <td class="bold rowToToggle">data2</td> </tr> <tr> <td>data1</td> <td class="bold rowToToggle">data2</td> </tr> </table> <input type="button" onclick="toggleByClass(true);" value="show"/> <input type="button" onclick="toggleByClass(false);" value="hide"/> </body> </html>

您可以通過以下方式使用 jQuery 中的名稱元素從輸入字段中獲取名稱值:

 var firstname = jQuery("#form1 input[name=firstname]").val(); //Returns ABCD var lastname = jQuery("#form1 input[name=lastname]").val(); //Returns XYZ console.log(firstname); console.log(lastname);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="form1" id="form1"> <input type="text" name="firstname" value="ABCD"/> <input type="text" name="lastname" value="XYZ"/> </form>

框架通常在表單中使用括號名稱,例如:

<input name=user[first_name] />

可以通過以下方式訪問它們:

// in JS:
this.querySelectorAll('[name="user[first_name]"]')

// in jQuery:
$('[name="user[first_name]"]')

// or by mask with escaped quotes:
this.querySelectorAll("[name*=\"[first_name]\"]")

我這樣做了並且有效:

$('[name="tcol1"]')

https://api.jquery.com/attribute-equals-selector/

您忘記了第二組引號,這使得接受的答案不正確:

$('td[name="tcol1"]') 

這是一個簡單的解決方案: $('td[name=tcol1]')

您可以將任何屬性用作帶有[attribute_name=value]的選擇器。

$('td[name=tcol1]').hide();

表現

今天(2020.06.16)我在 Chrome 83.0、Safari 13.1.1 和 Firefox 77.0 上對 MacOs High Sierra 上的選定解決方案進行了測試。

結論

按名稱獲取元素

  • getElementByName (C) 是所有瀏覽器對於大小數組最快的解決方案——但是我可能是某種延遲加載解決方案或者它使用一些帶有名稱元素對的內部瀏覽器哈希緩存
  • js-jquery混合方案(B)比querySelectorAll (D)方案快
  • 純 jquery 解決方案 (A) 是最慢的

按名稱獲取行並隱藏它們(我們從比較中排除預先計算的本機解決方案(I) - 理論上最快) - 它用作參考)

  • 令人驚訝的是,混合 js-jquery 解決方案 (F) 在所有瀏覽器上都是最快的
  • 令人驚訝的是,預先計算的解決方案 (I) 比大表 (.!!) 的 jquery (E,F) 解決方案慢 - 我檢查了 .hide() jQuery 方法在隱藏元素上設置樣式"default:none" - 但看起來他們找到了比element.style.display='none'更快的方法
  • jquery (E) 解決方案在大表上相當快
  • jquery (E) 和 querySelectorAll (H) 解決方案對於小表來說最慢
  • getElementByName (G) 和 querySelectorAll (H) 解決方案對於大表來說相當慢

在此處輸入圖像描述

細節

我按名稱( ABCD )對讀取元素執行兩個測試並隱藏該元素(E、F、G、H、I)

  • 小桌子 - 3 行 - 你可以在這里運行測試
  • 大表 - 1000 行 - 你可以在這里運行測試

下面的片段展示了使用過的代碼

 //https://stackoverflow.com/questions/1107220/how-can-i-select-an-element-by-name-with-jquery# // https://jsbench.me/o6kbhyyvib/1 // https://jsbench.me/2fkbi9rirv/1 function A() { return $('[name=tcol1]'); } function B() { return $(document.getElementsByName("tcol1")) } function C() { return document.getElementsByName("tcol1") } function D() { return document.querySelectorAll('[name=tcol1]') } function E() { $('[name=tcol1]').hide(); } function F() { $(document.getElementsByName("tcol1")).hide(); } function G() { document.getElementsByName("tcol1").forEach(e=>e.style.display='none'); } function H() { document.querySelectorAll('[name=tcol1]').forEach(e=>e.style.display='none'); } function I() { let elArr = [...document.getElementsByName("tcol1")]; let length = elArr.length for(let i=0; i<length; i++) elArr[i].style.display='none'; } // ----------- // TEST // ----------- function reset() { $('td[name=tcol1]').show(); } [A,B,C,D].forEach(f=> console.log(`${f.name} rows: ${f().length}`));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <div>This snippet only presents used codes</div> <table> <tr> <td>data1</td> <td name="tcol1" class="bold"> data2</td> </tr> <tr> <td>data1</td> <td name="tcol1" class="bold"> data2</td> </tr> <tr> <td>data1</td> <td name="tcol1" class="bold"> data2</td> </tr> </table> <button onclick="E()">E: hide</button> <button onclick="F()">F: hide</button> <button onclick="G()">G: hide</button> <button onclick="H()">H: hide</button> <button onclick="I()">I: hide</button><br> <button onclick="reset()">reset</button>

Chrome 上的示例結果

在此處輸入圖像描述

就個人而言,我過去所做的是給他們一個通用的類 ID 並用它來選擇它們。 這可能並不理想,因為他們指定了一個可能不存在的類,但它使選擇變得容易得多。 只要確保你的類名是獨一無二的。

即對於上面的示例,我將按類別使用您的選擇。 更好的做法是將類名從粗體更改為“tcol1”,這樣您就不會在 jQuery 結果中意外包含任何內容。 如果 bold 實際上指的是一個 CSS 類,您總是可以在類屬性中指定兩者 - 即 'class="tcol1 bold"'。

總之,如果您不能按名稱選擇,要么使用復雜的 jQuery 選擇器並接受任何相關的性能影響,要么使用類選擇器。

您始終可以通過包含表名來限制 jQuery 范圍,即 $('#tableID >.bold')

這應該限制 jQuery 搜索“世界”。

它仍然可以被歸類為一個復雜的選擇器,但它很快將任何搜索限制在 ID 為“#tableID”的表內,因此將處理過程保持在最低限度。

如果您在 #table1 中查找超過 1 個元素,則另一種方法是單獨查找,然后將其傳遞給 jQuery,因為這限制了范圍,但每次都節省了一些處理時間來查找它。

var tbl = $('#tableID');
var boldElements = $('.bold',tbl);
var rows = $('tr',tbl);
if (rows.length) {
   var row1 = rows[0]; 
   var firstRowCells = $('td',row1); 
}
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    var a= $("td[name=tcol3]").html();
    alert(a);

});

</script>


<table border="3">
<tr>    
    <td>data1</td>
    <td name="tcol1" class="bold"> data2tcol1</td>
</tr>
<tr>    
    <td>data1</td>
    <td name="tcol2" class="bold"> data2tcol2</td>
</tr>  
<tr>    
    <td>data1</td>
    <td name="tcol3" class="bold"> data2tcol3</td>
</tr>
</table>

這是可能有用的代碼。

您可以使用其 ID 屬性在 JQuery 中獲取該元素,如下所示:

$("#tcol1").hide();

您可以使用以下功能:

get.elementbyId();

暫無
暫無

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

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