简体   繁体   English

jQuery无法从函数内动态创建的字段获取输入值

[英]jquery can't get input value from dynamically created field within a function

'This is a little strange, and different than what I can find in the forums, but I encounter this problem again and again when I work with jQuery. “这有点奇怪,并且与我在论坛上可以找到的有所不同,但是当我使用jQuery时,我一次又一次遇到这个问题。

I have code that calls ajax and creates (on success) an input like: 我有调用ajax并创建(成功)输入的代码,例如:

Start Date: <input type="text" id="gr_start_dt" size=10>
<button onclick="reassign_u();">Execute</button>

In the main body of the HTML, I have a function like this: 在HTML主体中,我有一个像这样的函数:

<script type="text/javascript" language="javascript">
function reassign_u()
{
   alert($("#gr_start_dt").val());
}
</script>

This will alert to "undefined". 这将提醒“未定义”。

If I change the button in the ajax generated section to: 如果我将ajax生成部分中的按钮更改为:

<button onclick="alert($('#gr_start_dt').val());">Execute</button>

it will alert with the value of the box. 它将提示该框的值。

I can get the value from outside of the function, but not within the function. 我可以从函数外部获取值,但不能从函数内部获取值。

Am I missing something here? 我在这里想念什么吗? Is there some scope I'm not aware of with jquery and dynamically generated pages with ajax? 我在使用jquery和使用ajax动态生成的页面时是否不了解某些范围?

I'm using jquery 2.1.3 and 2.1.4, Firefox 39. 我正在使用jquery 2.1.3和2.1.4,Firefox 39。

I think that is because when the javascript function was cached into the browser the element $("#gr_start_dt") is not yet defined. 我认为这是因为当javascript函数缓存到浏览器中时,元素$(“#gr_start_dt”)尚未定义。 And calling the function will just call the function that was cached having the undefined element inside the alert function. 调用该函数将只调用在警报函数内具有未定义元素的已缓存函数。

So why not do it like this: 那么为什么不这样做呢?

below is the html 下面是html

Start Date: <input type="text" id="gr_start_dt" size=10>
<button onclick="reassign_u($('#gr_start_dt'));">Execute</button>

below is the javascript: 以下是javascript:

<script type="text/javascript" language="javascript">
function reassign_u(el)
{
   alert($(el).val());
}
</script>

Removing the the line: $("#invoice_detail_content").html(''); 删除该行: $("#invoice_detail_content").html(''); from the following function should resolve the issue. 从以下功能应该可以解决问题。 This line removes the the textbox in question. 此行将删除有问题的文本框。

function reassign_user2() { 
    $("#action_menu_container").hide();
    $("#invoice_detail_content").html(''); //<== REMOVE THIS
    $("#invoice_detail").show();
    $("#loading").show();

    console.log($("#group_start_dt"));

    alert($("#group_start_dt").val());


    $.ajax({
        url: "fetch.php",
        cache: false,
        method: "POST",
        data: {
            action: 'reassign_group',
            parameters: JSON.stringify(parameters)                        
        }                              
    })
    .done(function(result) {                                       
        $("#loading").hide();
        result = result.trim();
        if(result)
        {
            $("#invoice_detail_content").html(result);
        }
        else
        {
            $("#invoice_detail").hide();
            show_invoices($("#invoice_status_select").val());
        }
    })
    .fail(function( jqXHR, textStatus ) {
        $("#loading").hide();
        alert( "Request failed: " + textStatus );                                                 
    });
}

So I'm taking a bit of a stab at this so hopefully I don't get down voted :(, though I believe I have the answer to this question. 所以我对此有点怀疑,所以希望我不会被否决:(尽管我相信我已经回答了这个问题。

When the DOM tree is created on the first page load all of the javascript events are bound to the all their respective elements, thus your .val() isn't attaching to any dynamically generated elements, but, one thing I have noticed, is that if you dynamically add some javascript with that dynamically created element it will run its binding process right then and there and still work, which is what you have done by putting the alert($(element).val()) directly on the dynamically generated element. 当在第一页加载中创建DOM树时,所有javascript事件均绑定到其所有相应元素,因此您的.val()不会附加到任何动态生成的元素,但是,我注意到的一件事是如果您使用该动态创建的元素动态添加一些javascript,它将立即运行其绑定过程,然后仍然运行,这是通过将alert($(element).val())直接直接动态放置而完成的操作生成的元素。

Hopefully this helps you, if not somebody out there. 希望这对您有帮助,即使没有人在场。 I realized the answer is a bit late. 我意识到答案有点晚了。

I'm pretty sure creating things with JQuery/AJAX still causes it to enter the DOM, which means it can be gotten with $('selector') . 我敢肯定,使用JQuery / AJAX创建事物仍然会导致它进入DOM,这意味着可以使用$('selector')获得它。 So it should be just as straightforward usual. 因此,它应该和平常一样简单。

I used: 我用了:

<script>
    function on_clicked() {
       alert($("#text_input").val());
    }
</script>

<input type="text" id="text_input" size=10>
<button onclick="on_clicked();">Execute</button>

Working JSFiddle here . 在这里工作的JSFiddle。

I found that you have to declare the function before setting it to the onclick attribute. 我发现您必须在将函数设置为onclick属性之前对其进行声明。 Which makes sense. 有道理。 Otherwise I don't see any other big problems. 否则,我看不到任何其他大问题。

Update 更新资料

I am now making the <form> element "asynchronously" (I used a timeout to simulate AJAX. As long as the callback is declared before and in scope, it works fine. 现在,我使“ <form>元素“异步”(我使用超时来模拟AJAX。只要在范围之前和范围内声明了回调,它就可以正常工作。

JSFiddle JSFiddle

I've replicated what you are saying as well as I can, and it still works. 我已尽我所能复制了您的发言,但仍然有效。

It works for me. 这个对我有用。 May be you should put the js function in the same file from which you make the AJAX call. 可能是您应该将js函数放在进行AJAX调用的文件中。

here's the code 这是代码

index.php index.php

<head>
            function doSomeTheing() {
                $.ajax({
                    url: 'test01.php',
                    success: function (mydata) {
                        $('#container').html(mydata);
                    }
                });
            }

            function reassign_u()
            {
                alert($("#gr_start_dt").val());
            }
</head>
<body>
        <input type="button" id="abc" onclick="doSomeTheing()" value="test">
        <div id="container">

        </div>
</body>

test.php contains test.php包含

<?php

echo 'Start Date: <input type="text" id="gr_start_dt" size=10>
<button onclick="reassign_u();">Execute</button>';

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

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