我正在尝试比较 2 个值并在条件成立时更改其中一个的颜色。 但是我也有一个搜索栏,当它被包装在我使用 Rails 的 javascript 函数中的 <% if %> 语句中时,我无法访问标签值。
我原来是这样的代码
<% if track.user.username == current_user.username%>
<td class="track_table_current_user">
<span><%= track.user.username %></span>
</td>
<% else %>
<td class="td-userName">
<span class="track_table_user_name"><%= track.user.username %> </span>
</td>
<% end %>
我现在的三元数:
<td class="track_table_user_name <% track.user.username == current_user.username ? "this_current_user" : "other_user" %>">
<%= track.user.username %>
</td>
如果我使用 <% if %> <% else%>,我无法访问值的搜索函数:
function trackTableSearch() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("trackTableInput");
filter = input.value.toUpperCase();
table = document.getElementById("tracksTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
tdN = tr[i].getElementsByClassName("td-trackName")[0];
tdU = tr[i].getElementsByClassName("track_table_user_name")[0];
tdR = tr[i].getElementsByClassName("td-trackApproved")[0];
tdP = tr[i].getElementsByClassName("td-public")[0];
if ((tdN) || (tdU) || (tdR) || (tdP)) {
txtValueN = tdN.textContent || tdN.innerText;
txtValueU = tdU.textContent || tdU.innerText;
txtValueA = tdR.textContent || tdR.innerText;
txtValueP = tdP.textContent || tdP.innerText;
if (txtValueN.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
}else if (txtValueU.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else if (txtValueA.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
}else if (txtValueP.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
}
}
最佳答案
你可能想做这样的事情:
<td class="<%= track.user.username == current_user.username ? "track_table_current_user" : "td-userName" %>">
<%= track.user.username %>
</td>
参见 this answer要了解如何使用三元运算符,它在每种语言中的工作原理大致相同。
关于ruby-on-rails - 如何在 Ruby on Rails 中内联编写条件三元运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56744683/