如何在Angualar的jqLit​​e元素对象中按id查找元素

时间:2016-01-24 11:28:21

标签: javascript angularjs jqlite

我正在使用它:

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

然后在稍后的时间我想找到#pselect ID元素。 我的$vehicleTypeDropdown看起来就是 jqLit​​e对象: -

<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. jqLit​​e 文档中写道.find()方法只查找标记,而不是类或ID。那我怎么得到

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

    作为具有内容的jqLite对象?

  2. 如何找到#pselect的选项?我想手动删除它,请记住它可以在选项中以任何顺序。

2 个答案:

答案 0 :(得分:5)

使用public static async Task<bool> sleep_async(int ms){ await Task.Factory.StartNew(() => { System.Threading.Thread.Sleep(ms); }); return true; }

之类的# 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>

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

答案 1 :(得分:0)

  

如何在Angular的jqLit​​e元素对象

中按id查找元素

Id在页面上应该是唯一的,因此您只需使用document.getElementByIddocument.querySelector找到它,然后将其包装在jqLit​​e元素中。

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

这适用于:

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

但如果你有html:

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

你应该使用:

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

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

在这种情况下,您可以简单地使用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>

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

<小时/> 如果此代码有效:

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

你得到正确的对象,然后在你的页面上也包含完整的jQuery,因为你可以在jqLit​​e源代码中看到,find function很简单

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