无法从下划线模板中获取字段

I cannot get the fields from my underscore template

本文关键字:获取 字段 下划线      更新时间:2023-09-26

我有一段代码,它使用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">&times;</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注入到destination元素中。

更新#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

好吧,多亏了@Marcos pérez Gude的笔记,我找到了解决方案,如下所示:

console.log ( $( $.parseHTML( $ ( '#redirection_url_element' ).text() ) ).find( ':input' ) );

我知道它在某种程度上很丑陋,但它对我来说是有效的。你认为有更好的方法来实现以上目标吗?

不能选择<script>标记中的内容,因为它们不是DOM结构的一部分。这里有一条线索。

您是否尝试针对目标元素运行选择器?

样品:

<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元素内,浏览器就会删除它们。请参见此处。

尝试

$( '#redirection_url_element' ).find( 'input' )