Leo*_*ban 1 javascript python jquery whitespace
我找到了几个关于这个的答案(从文本中删除所有空格 [重复])
但是,没有一个答案在我的情况下有效,如果您有时间,请看一看..
第一步 Mako & Python 模板:为什么我在第一个空格中有新行和空格:
我们使用 Mako 模板和 Python 在我们的视图中生成数据:
<!-- 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)}'>
Run Code Online (Sandbox Code Playgroud)
最初我直接在<tr>标签中使用了 Python 代码,但是它生成了可见的换行符。现在使用<%def至少它将所有内容保留在 1 行,但 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);
//...
});
Run Code Online (Sandbox Code Playgroud)
当它遇到 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!")
Run Code Online (Sandbox Code Playgroud)
我在使用 self.param 时遇到了问题,所以它会跳过那个并上id = self.request.body线。

当然还有换行符和额外的空格:'(

请帮忙!
如果您将过滤后的值分配回变量,您的任何示例都将起作用:
var id = $tr.data('contact-id');
id = id.replace(/ /g, '');
Run Code Online (Sandbox Code Playgroud)
但是我建议您改用$.trim方法:
var id = $.trim( $tr.data('contact-id') );
Run Code Online (Sandbox Code Playgroud)
它将从值的开头和结尾删除空格。
最后 Python 有strip方法,它的作用完全相同:
id = id.strip()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5259 次 |
| 最近记录: |