简体   繁体   English

如何使用javascript / jquery中的某个类在HTML页面上选择所有角度字段?

[英]How do I select all angular fields on an HTML page using a certain class in javascript/jquery?

I am trying to format a field in the HTML of a site with Angular server side code. 我正在尝试使用Angular服务器端代码格式化网站HTML中的字段。 I want to write a javascript/jquery script on the HTML page to format the field from a decimal to a fraction. 我想在HTML页面上编写javascript / jquery脚本,以将字段的格式从十进制转换为小数。 I have javascript code to perform the conversion. 我有JavaScript代码来执行转换。 What I can't get to work is selecting each text element on the page. 我无法工作的是选择页面上的每个文本元素。 Each element I want to change has the ingredient-amount class. 我要更改的每个元素都有成分数量类。 However, when I select elements using that class, I don't get any results. 但是,当我使用该类选择元素时,没有任何结果。 Can someone help me? 有人能帮我吗?

First some background because it will explain why I don't just make a change in the controller. 首先介绍一些背景知识,因为这将解释为什么我不只是对控制器进行更改。 My company has received an Angular JS application hosted on Azure. 我的公司已收到托管在Azure上的Angular JS应用程序。 The controllers are all Angular JS. 控制器都是Angular JS。 We have the server side source code, but it is compiled into a dll and that dll is then put on Azure. 我们有服务器端源代码,但是将其编译为dll,然后将该dll放在Azure上。 Currently we don't have permission from the client to publish changes to the dll. 当前,我们没有客户端的权限将更改发布到dll。 So we're stuck with editing the HTML page (which is on Azure, but outside the dll). 因此,我们不得不编辑HTML页面(位于Azure上,但在dll之外)。 I need to find all of the decimal fields on the page and convert them to fractions. 我需要找到页面上的所有小数字段并将其转换为分数。 As I said, I have a script to do the conversion, but I don't know how to access each element. 如我所说,我有一个脚本来进行转换,但是我不知道如何访问每个元素。

The fields are created like so: 像这样创建字段:

                    <table class="component-ingredients-container">
                    <tr ng-repeat-start="component in currentRecipe.Components"
                        ng-show="component.Name">
                        <td>&nbsp;</td>
                        <td class="component-name-cell">
                            <span class="component-name">{{component.Name}}</span>
                        </td>
                    </tr>
                    <tr ng-repeat-end ng-repeat="ingredient in component.Ingredients">
                        <td>
                            <span class="ingredient-amount">{{ingredient.Amount}}</span>
                            <span class="ingredient-unit">{{ingredient.Unit}}</span>
                            <span>{{ingredient.Lookup.Name}}</span>
                            <div class="ingredient-preparation" ng-show="ingredient.Preparation">
                                <span>{{ingredient.Preparation }}</span>
                            </div>
                        </td>
                    </tr>
                </table>

The result is something like this: 结果是这样的:

Sauce

2.5 cups tomatoes 2.5杯西红柿

.5 tablespoon spices .5大汤匙香料

.125 ounces something else 0.125盎司其他

I want to grab those numbers (2.5, .5, and .125) so I can pass them to my conversion script. 我想获取这些数字(2.5,.5和.125),以便将其传递给我的转换脚本。

My first attempt was to use jquery, but I got an error saying $ was not defined (I tried jquery in place of $ with similar results). 我的第一个尝试是使用jquery,但是出现一个错误,提示未定义$(我尝试用jquery代替$,结果类似)。 I also tried adding script tags with links to the jquery code without success. 我还尝试添加带有指向jquery代码链接的脚本标签,但未成功。

        $(document).ready(function () {
        try
        {
            $('.ingredient-amount').each(function (ndx) {
                var org = $(this).text();
                console.log("Object:" + org);
            });
        }
        catch (ex)
        {
            console.log("Error:" + ex);
        }
    });

My conclusion was that Angular or some other code was causing a conflict. 我的结论是Angular或其他代码正在引起冲突。

I tried to write the query in javascript, which seemed to only find one instance of the class .ingredient-amount 我试图用javascript写查询,似乎只找到了类.ingredient-amount的一个实例。

    function r(f){/in/.test(document.readyState)?setTimeout(r,9,f):f()}
r(function () {
    try {
        var divs = document.querySelectorAll('.ingredient-amount');

        [].forEach.call(divs, function (div) {
            try {
                console.log("Inside");
                console.log(divs.text());
            }
            catch (ex) {
                console.log(ex);
            }
        });
    }
    catch (ex) {
        console.log(ex);
    }
});

I tried something different next. 接下来,我尝试了不同的方法。 I added an ID to the span tags and tried finding that specific ID. 我在跨度标签中添加了一个ID,并尝试查找该特定ID。 However, it couldn't be found. 但是,找不到。 I got a null as the result. 结果为空。

<span class="ingredient-amount" id="amount-{{$index}}">{{ingredient.Amount}}</span>

    function r(f) { /in/.test(document.readyState) ? setTimeout(r, 9, f) : f() }
r(function () {
    console.log("Ready");
    var div = document.getElementById('amount-0');
    console.log("Element: " + div);
    console.log("Got it!");
});

My conclusion is that I'm not selecting those angular fields correctly. 我的结论是我没有正确选择这些角场。 How can I do that? 我怎样才能做到这一点?

Update: 更新:

I was able to add a button and get that working. 我能够添加一个按钮并使它工作。 However, I'm not able to get any kind of on ready function working. 但是,我无法使任何形式的就绪功能正常工作。 I've tried (1.) jquery document ready; 我已经尝试过(1.)准备好jquery文档; jquery doesn't work, so that's a bust, (2.) The shortest ready, bind ready, and several others from here: $(document).ready equivalent without jQuery (3.) Just including the code outside a function as the last part of the script tag. jQuery不起作用,所以很失败,(2。)最短的就绪,绑定就绪,以及这里的其他几个: $(document).ready等效,没有jQuery (3.)只是将代码包含在函数之外脚本标签的最后一部分。

How can I get this code to work when the page opens instead of having to click a button? 当页面打开而不需要单击按钮时,如何使此代码起作用?

<button id='btnConvertToFractions' onclick="buttonConvert()">Convert to Fractions</button>


function buttonConvert()
{
    try
    {
        console.log("Convert started");
        var divs = document.querySelectorAll('.ingredient-amount');

        [].forEach.call(divs, function (div) {
            console.log("Before: " + div.textContent);
            div.textContent = Fraction(div.textContent);
            console.log("After: " + div.textContent);
        });
        console.log("Convert finished");
    }
    catch (ex)
    {
        console.log("Error: " + ex);
    }
};

You can use : 您可以使用 :

var amounts = document.getElementsByClassName("ingredient-amount");`

An example here: jsFiddle 此处的示例: jsFiddle

Here is the solution I came up with. 这是我想出的解决方案。 I found an angular document ready function, but at first it didn't seem to work. 我找到了一个有角度的文档准备就绪功能,但起初它似乎不起作用。 Then I found a suggestion online to add a timeout. 然后,我在网上找到了添加超时的建议。 Combining these worked. 结合这些工作。 The timeout seems to be giving the page the time to load all of the angular data elements (the ng-repeat div and its contents). 超时似乎使页面有时间加载所有角度数据元素(ng-repeat div及其内容)。

    angular.element(document).ready(
    setTimeout(
          function () {
              buttonConvert();
          }
        , 2000));

The "Angular way" to do this is to write a custom filter . 实现此目的的“角度方法”是编写自定义过滤器

For example: 例如:

angular.module('YourModule', []).
  filter('fraction', function() {
    return function(input) {
      var out = "",
          wholeNumber = parseInt(input, 10),
          decimals = input - wholeNumber,
          fraction = '';

      if (decimals === .5) {
        fraction = '1/2';
      }

      return out + wholeNumber + ' ' + fraction;
    }
  });

You can then use the filter directly in the AngularJS template: 然后,您可以直接在AngularJS模板中使用过滤器:

<span class="ingredient-amount">{{ingredient.Amount|fraction}}</span>

A little explanation... Each element in the View Template HTML is parsed when it's about to be added to the DOM. 一点解释...将要添加到DOM时,将解析View Template HTML中的每个元素。 As AngularJS parses each element, it looks for custom elements and attributes, and also for expressions : 当AngularJS解析每个元素时,它会查找自定义元素和属性以及表达式

{{ingredient.Amount}}

The actual value of ingredient.Amount is inserted into the element before it's added to the DOM. Ingredient.Amount的实际值会在元素添加到DOM之前插入到元素中。

All we've done is add a filter that formats the value of ingredient.Amount. 我们所要做的就是添加一个过滤器,该过滤器用于格式化Ingredient.Amount的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 JavaScript 中使用 querySelector 选择具有特定类的所有子元素,而不考虑它们在 HTML 中出现的顺序? - How can I select all child elements with a certain class using querySelector in JavaScript regardless of the order they appear in HTML? 如何选择页面上包含特定单词的所有链接? - How do I select all links on page that contain a certain word? 如何使用 jQuery 在 HTML 选择中突出显示某些选项 - How can I highlight certain options in a HTML select using jQuery 如何使用JavaScript,jQuery和HTML为所有已登录用户刷新页面(协作编辑)? - How can I refresh a page for all logged in users (collaborative editing) using JavaScript, jQuery and HTML? 如何使用jQuery将CSS类应用于某些元素? - How do I apply a css class to certain elements using jquery? 如何使用angular和javascript使我的mlab数据库显示在我的html页面上? - How do I get my mlab db to show up on my html page using angular and javascript? 如何在使用Javascript选择的html select元素中创建所有值 - How do I make all values in html select element selected using Javascript 在使用JavaScript或JQuery选择HTML中的选定项目之后,如何禁用项目? - How do I disable items after the selected item in an HTML select using JavaScript or JQuery? 通过JavaScript克隆html元素后,如何清除输入字段并选择字段? - How do I clear input fields and select fields after cloning html elements via JavaScript? 我如何使用jQuery / JavaScript使用Treetable插件影响/选择所有后代 - How do I affect/select all descendants with Treetable plugin using jQuery / javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM