2016-01-06 108 views
-2

我有一个名为shop_attributesjQuery和改变HTML输出

结构的表类如下:

<table class="shop_attributes"> 
    <tbody> 
    <tr class=""> 
     <th>Reserved</th> 
     <td> 
     <p>false</p> 
     </td> 
    </tr> 
    <tr class="alt"> 
     <th>Show Terms And Conditions</th> 
     <td> 
     <p>true</p> 
     </td> 
    </tr> 
    </td> 
    </tr> 
    </tbody> 
</table> 

使用jQuery我想要的虚假每个实例更改为不和的每个实例是的。

我有下面的代码,那里还没有。任何人都可以在这里提出问题。

(function($) { 
    $(document).ready(function() { 
     if ($('#tab-additional_information > table > tbody > tr:nth-child(2) > td > p').val() == "true" { 
      $('#tab-additional_information > table > tbody > tr:nth-child(2) > td > p').replaceWith("Yes") 
     } 
    }); 
}(jQuery)); 
+2

'p'标签不返回'VAL ()'。使用'text()'或'html()' –

+0

另外,你的HTML是无效的,你的JavaScript中有拼写错误。 – j08691

+0

为了与Quentin的答案一起提供一些建议,'val()'主要用于从表单元素(认为输入)获取值。你可以阅读它[这里](http://api.jquery.com/val/)。 –

回答

1

从我的评论:p标签不返回val()。使用text()html()

而且,由于没有其他人覆盖它的text()(和.html())功能允许您提供一个函数作为参数,而不是一个值。该函数的返回值用于替换文本。

这意味着你可以将其降低到:

$('table.shop_attributes p').text(function() { 
    if ($(this).text() == 'false') return 'no'; 
    if ($(this).text() == 'true') return 'yes'; 
}); 

甚至更​​短(如果该值只有truefalse):

$('table.shop_attributes p').text(function() { 
    return $(this).text() == 'true' ? 'yes' : 'no'; 
}); 
3

段落没有值。您需要.text()

您可能还希望设置文本.text("Yes")而不是用文本节点替换整个段落元素。

1

如上所述,val()用于输入。在处理段落时,您希望使用text()html()来读取值。您可以简单地循环和设置文本,而不是选择每个元素。 (假定有表中没有其他段落)

$(".shop_attributes p").each(
 
    function() { 
 
    var p = $(this); 
 
    var txt = p.text(); 
 
    var updated = txt === "true" ? "yes" : "no"; 
 
    p.text(updated); 
 
    } 
 
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table class="shop_attributes"> 
 
    <tbody> 
 
    <tr class=""> 
 
     <th>Reserved</th> 
 
     <td> 
 
     <p>false</p> 
 
     </td> 
 
    </tr> 
 
    <tr class="alt"> 
 
     <th>Show Terms And Conditions</th> 
 
     <td> 
 
     <p>true</p> 
 
     </td> 
 
    </tr> 
 
    </td> 
 
    </tr> 
 
    </tbody> 
 
</table>

1

正如评论所指出的那样,你不能使用.val()更改段落元素的含量。另外,正如我在评论中指出的那样,您的代码中存在拼写错误和错误。校正所有这一切,以下工作:

$('table.shop_attributes p').each(function() { 
 
    if ($(this).text() == 'false') $(this).text('no') 
 
    if ($(this).text() == 'true') $(this).text('yes') 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table class="shop_attributes"> 
 
    <tbody> 
 
    <tr class=""> 
 
     <th>Reserved</th> 
 
     <td> 
 
     <p>false</p> 
 
     </td> 
 
    </tr> 
 
    <tr class="alt"> 
 
     <th>Show Terms And Conditions</th> 
 
     <td> 
 
     <p>true</p> 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>