【问题标题】:Prevent Line Breaks from Javascript alert防止 Javascript 警报中的换行符
【发布时间】:2015-04-07 13:52:30
【问题描述】:

我有一些代码用于识别在下拉菜单中单击了哪些链接,并读回层次结构。 (父母,孩子,孙子)。代码运行良好,我不想更改它。

问题是 html 中有换行符和回车符,并且它包含在我的警报中,导致报告出现问题。

有没有办法让我使用这个现有的代码,并添加一些东西来忽略/去除任何中断或回车?

 $("ul#menudropd .myclass li a").click(function() {
var granchild = $(this).text(),
parent = $(this).closest(".anotherclass").find("a:first").text();
  if ($(this).hasClass("subbold")) {
            child = "";
  } else {
child = $(this).closest("li").prevAll("li:has(a.subbold)").first().find('a').text();
  }
alert(parent + ":" + child + ":" + grandchild);
});

一些警报会像这样返回: "ClickedParent ::

ClickedGrandChild"

我每次都想要:“ClickedParent : : ClickGrandChild”。

【问题讨论】:

    标签: javascript jquery string alert line-breaks


    【解决方案1】:

    这将删除回车和换行代码:

    alert((parent + ":" + child + ":" + grandchild).replace(/(\n|\r)/g,''));
    

    【讨论】:

    • 完美。我在其他地方发现了替换代码,但不确定在我的代码中粘贴它的位置。工作得很好。谢谢!
    【解决方案2】:

    这是因为child 未定义或为空。您需要检查 child 是否为 undefined 或 null 并且基于此您可以显示警报。像这样的,

    if(child!=null && typeof child != 'undefined')
     alert(parent + ":" + child + ":" + grandchild);
    else
     alert(parent + ":" + " " + ":" + grandchild);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多