我找到了几个关于此问题的答案(Remove ALL white spaces from text [duplicate])
但是,没有一个答案对我的情况有效,如果您有时间,请看一下。
Mako 和 Python 模板的第一步:为什么我在第一个空格中有新行和空白:
我们使用 Mako 模板和 Python 在 View 中生成数据:
<!-- The Python def on the page that pulls in the correct id -->
<%def name="pull_id(contact)">
% if "member" in contact:
${contact["member"]["id"]}
% else:
${contact["id"]}
% endif
</%def>
<%def name="render_contact_row(contact)">
<!-- the def returns the id here -->
<tr data-contact-id='${pull_id(contact)}'>
本来我直接把Python代码放在 <tr>
中然而,标签产生了可见的换行符。现在使用 <%def
至少它把所有内容都放在一行上,但是 HTML 中仍然有一些额外的空格
现在是我的 jQuery:
$('.btn_hide').live("click", function(event) {
// gets the id number from the data tag in html
var $tr = $(this).closest("tr");
var id = $tr.data('contact-id');
// tried this
id.replace(/ /g,'');
// then this
id.replace(/\s+/, "");
// even this
id.replace(/\s/g, "");
// still prints out white space :'(
console.log(id);
//...
});
当它到达 console.log 行时,chrome 会打印出以下内容:
明显有换行符和额外的空白
最后它再次袭击了Python:
@view_config(route_name="contacts_hide", request_method='POST')
def hide(self):
id = self.param("id")
if id is None:
id = self.request.body
if id.isdigit() is True:
id = int(id)
if id is None:
raise Exception("The contact id parameter cannot be null!")
我在使用 self.param 时遇到了问题,因此它将跳过该问题并点击 id = self.request.body
线。
当然还有换行符和额外的空白:'(
请帮忙!
最佳答案
如果您将过滤后的值分配回变量,您的任何示例都将起作用:
var id = $tr.data('contact-id');
id = id.replace(/ /g, '');
但是我建议您使用 $.trim
方法:
var id = $.trim( $tr.data('contact-id') );
它将删除值开头和结尾的空格。
Python 最后有 strip
方法,它的作用完全相同:
id = id.strip()
关于javascript - 如何从 jQuery 中的变量中删除换行符和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22538793/