如何在Angualar的jqLite元素对象中按id查找元素

How to find element by id in Angualar's jqLite element object

本文关键字:元素 对象 id 查找 jqLite Angualar      更新时间:2023-09-26

我正在使用这个:

$vehicleTypeDropdown = element.find(".vehicleTypeDropdown");

然后在稍后的时间点,我想找到 #pselect ID 元素。我的$vehicleTypeDropdown看起来像这样,它是jqLite对象:-

<select class="vehicleTypeDropdown" id="vehicleType">
<option id="#pselect" value="">Please Select</option>
<option ng-repeat="types in selectedType" value="Vt3" class="ng-scope ng-binding">vt3</option>
<option ng-repeat="types in selectedType" value="Vt4" class="ng-scope ng-binding">vt4</option>
</select>

有两个问题——

  1. jqLite 文档中写道.find()方法只查找标记,而不查找类或 id。那么我该如何获得

    $vehicleTypeDropdown = element.find(".vehicleTypeDropdown");

    作为内容jqLite对象?

  2. 我怎样才能找到带有#pselect的选项?我想手动删除它,请记住它可以在选项中按任何顺序排列。

使用 id 而不#,就像 id="pselect"

<select class="vehicleTypeDropdown" id="vehicleType">
    <option id="pselect" value="">Please Select</option>
    <option ng-repeat="types in selectedType" value="Vt3" class="ng-scope ng-binding">vt3</option>
    <option ng-repeat="types in selectedType" value="Vt4" class="ng-scope ng-binding">vt4</option>
</select>

像这样的捕获元素

var elem = angular.element(document.querySelector('#pselect'))
elem.remove()

http://jsfiddle.net/vorant/4sbux96k/1/

如何在 Angular 的 jqLite 元素对象中按 id 查找元素

Id在页面上应该是唯一的,所以你可以用document.getElementById或document.querySelector找到它,然后将其包装在jqLite元素中。

var pselect = angular.element(document.getElementById('pselect'));

这适用于:

<option id="pselect" value="">

但是如果你在 HTML 中有:

<option id="#pselect" value="">

您应该使用:

var pselect = angular.element(document.getElementById('#pselect'));

我只想找到它并动态删除它,以便用户无法在选择中看到该选项。

在这种情况下,您可以简单地使用ng-if指令:

<select class="vehicleTypeDropdown" id="vehicleType">
    <option id="pselect" ng-if="condition" value="">Please Select</option>
    <option ng-repeat="types in selectedType" value="Vt3" class="ng-scope ng-binding">vt3</option>
    <option ng-repeat="types in selectedType" value="Vt4" class="ng-scope ng-binding">vt4</option>
</select>

如果条件为 true,则在 DOM 中添加元素,如果不是 - 不是


如果此代码有效:
$vehicleTypeDropdown = element.find(".vehicleTypeDropdown");

并且你得到正确的对象,然后在你的页面上也包含了完整的jQuery,因为正如你在jqLite源代码中看到的那样,查找功能很简单

find: function(element, selector) {
    if (element.getElementsByTagName) {
        return element.getElementsByTagName(selector);
    } else {
        return [];
    }
},