javascript
  • jquery
  • 2016-01-25 45 views 0 likes 
    0

    外部系统生成翻译并用页面上的span文本替换文字。它适用于大多数场所,但它不适用于select中的选项。他们只支持文本。因为我的网页有问题,像这里SQL Fiddle sample用span文本选择的选项

    <select class="ProductInfo" > 
        <option value=""></option> 
        <option value="0">&lt;span class='translation'&gt;Opt1&lt;/span&gt;</option> 
        <option value="1">&lt;span class='translation'&gt;Opt2&lt;/span&gt;</option> 
    </select> 
    

    我想要一些jQuery的/ JavaScript的功能,将只用文本替换选项内容,并删除上面的包装。

    预期的结果:

    <select class="ProductInfo" > 
        <option value=""></option> 
        <option value="0">Opt1</option> 
        <option value="1">Opt2</option> 
    </select> 
    

    回答

    3

    最好是在模板本身来解决,如果这是不可能的,你可以尝试这样

    $('.ProductNoInfo option').text(function(i, t) { 
     
        return $(t).text() 
     
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
     
    <select class="ProductNoInfo"> 
     
        <option value=""></option> 
     
        <option value="0">&lt;span class='translation'&gt;Opt1&lt;/span&gt;</option> 
     
        <option value="1">&lt;span class='translation'&gt;Opt2&lt;/span&gt;</option> 
     
    </select>

    0

    试试这个,

    $('.ProductNoInfo option').each(function(){ 
        $(this).text($(this).find('span').text()); 
    }); 
    
    +0

    一点解释将是有益的。你的解决方案是什么?它如何解决这个问题? – showdev

    2

    尝试使用decodeURICompoenent

    $("select option").each(function() { 
     
        this.textContent = $(decodeURIComponent(this.textContent)).text() 
     
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
     
    <select class="ProductInfo" > 
     
        <option value=""></option> 
     
        <option value="0">&lt;span class='translation'&gt;Opt1&lt;/span&gt;</option> 
     
        <option value="1">&lt;span class='translation'&gt;Opt2&lt;/span&gt;</option> 
     
    </select>

    0
    <html> 
    <head> 
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script> 
    
    <script> 
    
        $(document).ready(function(){ 
         $('.ProductInfo option').each(function() { 
          this.textContent = $(decodeURIComponent(this.textContent)).text() 
         }); 
    
    
         }); 
    </script> 
    </head> 
    <body> 
    
    <select class="ProductInfo" > 
        <option value=""></option> 
        <option value="0">&lt;span class='translation'&gt;Opt1&lt;/span&gt;</option> 
        <option value="1">&lt;span class='translation'&gt;Opt2&lt;/span&gt;</option> 
    </select> 
    </body> 
    </html> 
    
    相关问题