jQuery选择器无法在DOM中找到添加的元素

时间:2015-01-14 17:24:18

标签: javascript jquery dom selector

我知道解决方案是jQuery.on - 函数,但它不会像我预期的那样工作。

以下问题: 我通过Websocket(JSON)数据提取并在文档就绪函数内部构建我的页面(出于连接原因)。 这意味着我通过jQuery.append() - 函数添加几个输入字段,并在按下SET按钮时尝试访问select-input。访问选择输入失败。 我选择了body作为父元素,其他每个表单字段都应该在其中。

出于演示原因,我删除了Websocket-Functions。我已经硬编码了形式,因为它将是真实的。调试消息显示在firebug-console中。 这是小提琴:http://jsfiddle.net/gLauohjd/

这是我访问选择输入的方式

$("body").on('click', ':button', function () {
    console.log( $( this ).text() ); //Value of the pressed button
    var ip = $(this).attr('ip');
    var selectvalue = "#" + "modeselect" + ip;
    console.log(selectvalue); //Print the selector to verify it is ok
    console.log($(selectvalue).val()); //fails ->not found in DOM

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

要使用jQuery选择标记,请仅使用标记名称。

$("body").on('click', 'button', function () { .. } // any button clicked on body

至于实际检索值,除非你逃脱了点,否则你将无法这样做。

$("#modeselect127\\.0\\.0\\.1").val();

您可以使用以下内容:

var selectvalue = "#" + "modeselect" + ip.replace(/\./g, "\\\\.");

希望这有帮助。