简体   繁体   English

当值大于时,为什么不执行我的jQuery函数?

[英]Why isn't my jQuery function being executed when a value is greater than?

I have a table with a row defined like this: 我有一个表,其行定义如下:

<tr>
  <td id="to-watch">
      @Model.Results.Seats
  </td>
</tr>

Edit: The table values are being updated by ajax calls to an action which is returning data to the table in a partial 编辑:通过ajax调用来更新表值,该操作将部分返回数据到表中

I want to log to the console when the value is greater than 2, here is the jQuery code I have: 当值大于2时,我想登录控制台,这是我拥有的jQuery代码:

$('#to-watch')
    .change(function () {
        if ($('#to-watch').val() > 2) {
            console.log("************ WINNER ***************");
        }
    });

I have checked in Chrome debugging tools nothing is being logged to the console when the value is greater than 2 - I rarely use jQuery / JavaScript, and after some looking, haven't been able to find the answer.. 我已经检查了Chrome调试工具的值大于2时什么都没有记录到控制台-我很少使用jQuery / JavaScript,并且经过一番寻找,却找不到答案。

Edit: I'm making the ajax call like this: 编辑:我正在这样的ajax调用:

$(document).ready(function () {

    (function loop(i) {
        setTimeout(function () {
            callAjax(i);
            //console.log("works " + i);
        },
            500); // ms
        function callAjax(i) {
            $.ajax({
                url: '/Home/StartElection',
                type: 'POST',
                data: "test",
                async: true
            })
                .done(function (partialViewResult) {
                    $("#partialTable").html(partialViewResult);
                }).always(function () {
                    if (--i) loop(i);
                });
        };
    })(650);
});

There are a couple of problems here. 这里有两个问题。


Firstly, the change event is for input fields. 首先, change事件用于输入字段。 It will execute the callback whenever the value of the input field changes. 只要输入字段的值更改,它将执行回调。

There is an equivalent for when any html changes, using Mutation Observers , but it's overly complex for this scenario, as you know when the html changes, and it is done via your code. 当使用mutation Observers进行 html更改时,有一个等效项,但是对于这种情况来说,它过于复杂,因为您知道html何时更改,并且通过代码完成。


Secondly, you are attaching an event listener to #to-watch , which I assume is nested inside #partialTable . 其次,您将事件侦听器附加到#to-watch ,我认为它嵌套在#partialTable Now we already know the change event won't work anyway, but even if this was an input field, we would have the following problem: 现在我们已经知道change事件将无法正常工作,但是即使这是一个输入字段,我们也会遇到以下问题:

  1. Attach listener to DOM element with #to-watch 使用#to-watch将侦听器附加到DOM元素
  2. Make ajax call 拨打ajax
  3. On return of ajax call, replace all of #partialTable with a new version of it. 返回ajax调用后,将其所有#partialTable替换为新版本。
  4. The old #to-watch element is now gone, and so is it's event listener. 现在,旧的#to-watch元素消失了,事件监听器也消失了。 It can't be triggered anymore. 无法再触发它。

The solution to this is called event delegation . 解决此问题的方法称为事件委托 Meaning you attach the listener to a parent element that doesn't change, and it checks if any child elements matching the selector are changed. 意味着您将侦听器附加到一个不变的父元素,并检查是否有任何与选择器匹配的子元素被更改。 This means that id the child elements were changed dynamically, the listener will still work. 这意味着id子元素是动态更改的,侦听器仍将起作用。


Then there are also the aforementioned: 然后还有前面提到的:

$('...').text() will give you the contents of any DOM element, where as $('...').val() will give the value of an input field $('...').text()将为您提供任何DOM元素的内容,其中$('...').val()将为您提供输入字段的值

JQUERY .text() docs JQUERY .text()文档

JQUERY .val() docs JQUERY .val()文档

You want to do a numerical comparison ( X > Y ), so you should convert the string "2" which is the text of $('#to-watch') into an integer with parseInt(x) 您想进行数值比较( X > Y ),因此应将字符串$('#to-watch')的字符串“ 2”转换为带有parseInt(x)的整数


The solution to your problem 解决问题的方法

When you update the #partialTable , you know that the #to-watch element has received a new value, so now is the time to check it: 当您更新#partialTable ,您知道#to-watch元素已收到一个新值,因此现在该检查它了:

      function callAjax(i) {
        $.ajax({
            url: '/Home/StartElection',
            type: 'POST',
            data: "test",
            async: true
        }).done(function (partialViewResult) {
            $("#partialTable").html(partialViewResult);
            if (parseInt($('#to-watch').text()) > 2) {
              console.log("************ WINNER ***************");
            }
        }).always(function () {
            if (--i) loop(i);
        });
    };

您可以尝试使用JQuery函数中的text()代替val()。

Please try text() . 请尝试使用text()

text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML markup)
val() - Sets or returns the value of form fields

Please check the this link for DOM Insertion using Jquery 请检查此链接以使用Jquery进行DOM插入

$(body).on('mycontentchange','#to-watch', function() {//make sure #to-watch is available in DOM while binding, or use `on` to delegate the event
    console.log('new content updated',$('#to-watch').text());
});

            .done(function (partialViewResult) {
                $("#partialTable").html(partialViewResult);
                $('#to-watch').trigger('mycontentchange');
            }).always(function () {
                if (--i) loop(i);
            });

This is just a direct answer to the question, you probably have better ways to solve the problem :) This is an overkill as @jeremy pointed out considering your continuous polling. 这只是问题的直接答案,您可能有解决问题的更好方法:) @jeremy指出考虑连续轮询,这实在太过分了。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM