简体   繁体   English

适用于香草javascript,但不适用于jquery

[英]Works with vanilla javascript but not jquery

I'm trying to attach VKI (see http://www.greywyvern.com/code/javascript/keyboard ) to an element that's being dynamically added to the DOM via Javascript. 我试图将VKI(请参阅http://www.greywyvern.com/code/javascript/keyboard )附加到通过Javascript动态添加到DOM的元素上。

Essentially, it's a table with only one row to begin with and there's "Add Row" and "Delete Row". 本质上,它是一个表,只有一行开始,并且有“添加行”和“删除行”。 It gets tricky because each row has an input that needs VKI attached to it. 之所以变得棘手,是因为每一行都有一个需要VKI附加的输入。

Below is just a snippet of my otherwise larger code to handle adding and deleting row. 以下只是我的其他较大代码的一小段,用于处理添加和删除行。

$('#add-passenger-row').click(function(){
    get_lastID();
    $('#passenger-information tbody').append(newRow);


    // this doesn't work --- throws "Uncaught TypeError: undefined is not a function" 
    var myInput = $(newRow).find('#myInput');
    VKI_attach(myInput);

    // this works
    var myInput = document.getElementById('myInput');
    VKI_attach(myInput);

});

My question is... how can I make this work? 我的问题是...我该如何进行这项工作? ie attach VKI to each input in the row that's added dynamically when a user clicks "Add Row" 即,将VKI附加到用户单击“添加行”时动态添加的行中的每个输入上

I can create JSBin if question is not clear enough. 如果问题不清楚,我可以创建JSBin。

Try: 尝试:

var myInput = $(newRow).find('#myInput').get(0);
VKI_attach(myInput);

.get() retrieves the DOM element from a jQuery object. .get()从jQuery对象检索DOM元素。 VKI is not a jQuery widget, so it doesn't work with jQuery objects, it expects raw DOM elements. VKI不是jQuery小部件,因此它不适用于jQuery对象,它需要原始DOM元素。

I think d-bro82 and ZiNNED are both right, but try var myInput = $('#myInput')[0]; 我认为d-bro82和ZiNNED都正确,但请尝试var myInput = $('#myInput')[0]; Since VNK_attach only accepts a dom element, the [0] should remove the jQuery wrapper 由于VNK_attach仅接受dom元素,因此[0]应该删除jQuery包装器

Try 尝试

var myInput = $('#myInput');

Good luck 祝好运

The reason the jQuery variant isn't working is because $(newRow).find('#myInput') is not the same as document.getElementById('myInput') . jQuery变体不起作用的原因是因为$(newRow).find('#myInput')document.getElementById('myInput') See this SO question . 看到这个问题 Apparently VKI_attach only accepts a DOM-element and not a jQuery wrapper element. 显然,VKI_attach仅接受DOM元素,而不接受jQuery包装器元素。

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

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