【问题标题】:jQuery - replacing spans parent text is removing the span elements? [duplicate]jQuery - 替换跨度父文本正在删除跨度元素? [复制]
【发布时间】:2016-02-05 03:12:27
【问题描述】:

我有一些代码替换了 TD 中的文本,但它也删除了 TD 中的其他元素,例如跨度,有什么方法可以替换文本吗?

替换前

<td>
    <span alt="Expand the sublist of items" title="Expand the sublist of items" id="on_user_81257937_1" class="cm-combination-carts" onclick="Tygh.$.ceAjax('request', 'admin.php?dispatch=cart.cart_list&amp;user_id=81257937&amp;c_company_id=1', {result_ids: 'cart_products_81257937_1,wishlist_products_81257937_1', caching: true});"><span class="exicon-expand"></span></span>
    <span alt="Collapse the sublist of items" title="Collapse the sublist of items" id="off_user_81257937_1" class="hidden cm-combination-carts"><span class="exicon-collapse"></span></span>

    Unregistered customer        
</td>

用我的 JS 替换后

<td>James Murphy</td>

预期结果

<td>
    <span alt="Expand the sublist of items" title="Expand the sublist of items" id="on_user_81257937_1" class="cm-combination-carts" onclick="Tygh.$.ceAjax('request', 'http://beanbags.ambientlounge.com/admin.php?dispatch=cart.cart_list&amp;user_id=81257937&amp;c_company_id=1', {result_ids: 'cart_products_81257937_1,wishlist_products_81257937_1', caching: true});"><span class="exicon-expand"></span></span>
    <span alt="Collapse the sublist of items" title="Collapse the sublist of items" id="off_user_81257937_1" class="hidden cm-combination-carts"><span class="exicon-collapse"></span></span>

    James Murphy       
</td>

Smarty/JS

{assign var="ac_firstname" value=$customer.user_id|fn_get_ac_firstname}
{assign var="ac_lastname" value=$customer.user_id|fn_get_ac_lastname}

{if !empty($ac_firstname) || !empty($ac_firstname)}
    <script type="text/javascript">

        $(document).ready(function(){

            $('#off_user_{$customer.user_id}_1').parent().text('{$ac_firstname} {$ac_lastname}');

        });

    </script>
{/if}

【问题讨论】:

  • 删除.parent()或在.text()之前添加.find(jquery_selector_for_span)
  • 用一个类将要替换的文本包装在 span 中,并以该 span 为目标。
  • 我不能修改模板作为它的核心模板,因为它会在软件更新时被替换,因此尝试这个 JS hack / Smarty hack 解决方案。如果我删除父级不起作用,我唯一可以附加 JS 的是跨度 ID,所以需要选择它,并仅替换其中的文本而不删除其他元素
  • 我更新了预期的问题,以便更好地了解我的意思
  • 获取对文本节点的引用并更新它 - 各种现有的 Stack Overflow 问题可以帮助解决这个问题,我已经关闭了这个问题作为我找到的第一个问题的副本。或者先分离跨度,然后更新文本,然后重新添加跨度。

标签: javascript php jquery html smarty


【解决方案1】:

解决方案是:

<script type="text/javascript">

    $(document).ready(function(){

        $('#off_user_{$customer.user_id}_1').parent().contents().last()[0].textContent="{$ac_firstname} {$ac_lastname}";

    });

</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-09
    • 2018-01-21
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 2013-06-28
    相关资源
    最近更新 更多