如何阻止 jQuery 从 .html() .val() .text() 等格式化代码返回制表符和空格

发布于 2024-08-27 17:51:05 字数 699 浏览 3 评论 0原文

我有一个 html 表格:

<table><tr>
 <td>M1</td>
 <td>M2</td>
 <td>M3</td>
 <td>M4</td>
</tr></table>

和一个简单的 jQ 脚本:

$('td').click(function(){ alert( $(this).html() ); });

效果很好......但在现实世界中,我有数百个表格单元格,并且代码在某些地方的格式不正确,因为有几个人编辑了页。

因此,如果 html 是:

     <td>
                     M1         

             </td>

那么al​​ert() 就会给我所有制表符、回车符和空格:

Javascript Alert http:// bit.ly/9B0Xon

如何才能仅获取不包含制表符和空格的文本?我尝试过 .html()、.val()、.text() 无济于事。谢谢!

I've got an html table:

<table><tr>
 <td>M1</td>
 <td>M2</td>
 <td>M3</td>
 <td>M4</td>
</tr></table>

and a simple jQ script:

$('td').click(function(){ alert( $(this).html() ); });

That works just fine.... but in the real world, I've got several hundred table cells and the code is formatted improperly in places because of several people editing the page.

So if the html is:

     <td>
                     M1         

             </td>

then the alert() is giving me all the tabs and returns and spaces:

Javascript Alert http://bit.ly/9B0Xon

What can I do to get ONLY the text without the tabs and spaces? I've tried .html(), .val(), .text() to no avail. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

绝不放开 2024-09-03 17:51:05

jQuery 有内置修剪函数,$.trim(),你可以像这样使用它:

$('td').click(function() {  alert( $.trim($(this).html()) ); });

jQuery has a built-in trim function, $.trim(), you can use it like this:

$('td').click(function() {  alert( $.trim($(this).html()) ); });
氛圍 2024-09-03 17:51:05

Nick 和 Darin 发布了一种从内容的开头和结尾修剪空白的好方法,但如果中间有很多空白,请以此为例:

<div>
             M1
                                                  M2
     </div>

您可以使用此修剪所有空白组合:

$('div').click(function() {
 var html = $.trim($(this).html().replace(/(\s+)/g,' '));
 alert(html);
})

Nick and Darin posted a great way to trim the white space from the beginning and end of the content, but in case you have a lot of white space in the middle, say this as an example:

<div>
             M1
                                                  M2
     </div>

You can trim all the white space using this combination:

$('div').click(function() {
 var html = $.trim($(this).html().replace(/(\s+)/g,' '));
 alert(html);
})
遗弃M 2024-09-03 17:51:05

您可以修剪字符串:

String.prototype.trim = function () {
    return this.replace(/^\s*/, '').replace(/\s*$/, '');
};

并像这样使用它:

$('td').click(function() { 
    var html = $(this).html().trim();
    alert(html); 
});

You can trim the string:

String.prototype.trim = function () {
    return this.replace(/^\s*/, '').replace(/\s*$/, '');
};

and use it like this:

$('td').click(function() { 
    var html = $(this).html().trim();
    alert(html); 
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文