输入键的两个数字的百分比 [英] percentage of two number with enter key works
问题描述
我有一张包含< tr>
和< td>
的表格,我展示了在第三个< td>
中售出的门票的百分比。我的代码正常工作,直到我在每个< td>
中的< br />
标记后输入。例如,如果您在每个< br />
标记后按Enter键,我的代码将正常工作,否则它将无效并且不会计算两个数字的百分比。如何定义不考虑每个< td>
之间的输入和空格的代码?
这是我的代码段:
I have a table that consists of <tr>
and <td>
's and I show the percentage of the sold tickets in the third <td>
. My code works correctly until I have an enter after <br/>
tag in each <td>
. For instance, if you press an enter key after each <br/>
tag my code works correctly otherwise it does not work and does not calculate the percentage of two number. how can I define to my code that does not consider the enter and space between each <td>
?
here is my snippet :
$('table tbody tr').each(function() {
var $this = this,
td2Value = $('td:nth-child(2)', $this).text().trim().split(/\D+/);
$('span.result', $this).each(function(index, element) {
let v = $('td:nth-child(1)', $this).text().trim().split(/\r?\n/);
if (v[index] != null && v[index].trim() == "Mytext") {
v[index] = td2Value[index];
}
if (v[index] != null) {
$(element).html(Math.round((td2Value[index] * 100 / v[index]) || 0) + '%');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<th> avalable</th>
<th> sold</th>
<th> result </th>
</tr>
</thead>
<tbody>
<tr>
<td>
10<br/>Mytext<br>
</td>
<td>
5<br/> 2
<br/>
</td>
<td>
<span class="result"></span><br/>
<span class="result"></span><br/>
</td>
</tr>
</tbody>
</table>
推荐答案
问题在于您的正则表达式
。
let v = $('td:nth-child(1)', $this).text().trim().split(/\r?\n/);
此行仅返回值,但连接。
This line only returns the values, but concatenated.
你想要的是一个非常基本的正则表达式(\d +)
这将只匹配
位数(全部你需要的是在一个字符串中分隔整数和文本。)
What you want is a very basic regex (\d+)
this will match only
digits(All you need is to separate integers and text in a string).
使用它:
let v = $('td:nth-child(1)', $this).text().trim().split(/(\d+)/).filter(v => v);
$('table tbody tr').each(function() {
var $this = this,
td2Value = $('td:nth-child(2)', $this).text().trim().split(/\D+/);
$('span.result', $this).each(function (index, element) {
let v = $('td:nth-child(1)', $this).text().trim().split(/(\d+)/).filter(v => v);
if(v[index] != null && v[index].trim() == "Mytext")
{
v[index] = td2Value[index];
}
if(v[index] != null )
{
$(element).html(Math.round((td2Value[index] * 100 / v[index]) || 0) + '%');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<th> avalable</th>
<th> sold</th>
<th> result </th>
</tr>
</thead>
<tbody>
<tr>
<td>
10<br/>Mytext<br/></td>
<td> 5<br/>2<br/></td>
<td>
<span class="result"></span><br/>
<span class="result"></span><br/>
</td>
</tr>
</tbody>
</table>
这篇关于输入键的两个数字的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!