我有一个代码,使用underscore
框架在页面中动态附加表单字段组,我在获取模板的输入字段时遇到问题,所以我不知道我是否在做某事错了,我看不到。
underscore
模板如下所示:
<script type="text/template" id="redirection_url_element">
<tr>
<td>
<input type="text" class="regular-text" placeholder="<?php esc_attr_e( 'Enter the redirection URL', 'WPL' ); ?>" value="<%= (typeof( redirection_url ) !== 'undefined') ? redirection_url : '' %>" data-name="redirection_url" data-group="redirection" />
</td>
<td>
<input type="text" class="regular-text" placeholder="<?php esc_attr_e( 'Weight', 'WPL' ); ?>" value="<%= (typeof( redirection_weight ) !== 'undefined') ? redirection_weight : '' %>" data-name="redirection_weight" data-group="redirection" />
</td>
<td>
<i class="remove-parent-row">×</i>
</td>
</tr>
</script>
所以在我的javascript代码中,我执行以下操作:
console.log ( $ ( '#redirection_url_element' ).find( ':input' ) );
我得到以下结果:
prevObject: e.fn.init[1], context: document, selector: "#redirection_url_element :input"]
context: document
length: 0
prevObject: e.fn.init[1]
selector: "#redirection_url_element :input"
__proto__: m[0]
似乎无法找到输入字段。如果您看到长度为0
。
更新#1
我使用模板的方式如下:
var $template_result = _.template ( $ ( '#redirection_url_element' ).html (), $data )
这就是我如何动态地将模板翻译成HTML而我不使用backbone
。我只是将$template_result
注入目标元素。
更新#2
所以,@ Wolff,表格如下:
<table class="repeater_table">
<tbody id="redirection_url_container">
<tr>
<td>
<input type="text" class="regular-text" placeholder="Enter the redirection URL" value="" data-name="redirection_url" data-group="redirection">
</td>
<td>
<input type="text" class="regular-text" placeholder="Weight" value="" data-name="redirection_weight" data-group="redirection">
</td>
<td>
<i class="remove-parent-row">×</i>
</td>
</tr>
</tbody>
</table>
更新#3
好的,我找到了解决方案,感谢@MarcosPérezGude音符,它就像是:
console.log ( $( $.parseHTML( $ ( '#redirection_url_element' ).text() ) ).find( ':input' ) );
我知道它有些丑陋,但它确实适合我。你认为有没有更好的方法来实现上述目标?
答案 0 :(得分:0)
您无法在<script>
标记内选择内容,因为它们不是DOM结构的一部分。 There's a thread about it here
您是否尝试针对目标元素运行选择器?
样品:
<div id="test"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(function() {
$('#test').html('<span id="foo">Foo bar</span>');
console.log($('#foo'));
});
</script>
请注意,如果tr
元素不在table
元素内,则会删除它们。 See here
答案 1 :(得分:-1)
尝试
$( '#redirection_url_element' ).find( 'input' )