单击时将文本附加到文本区域?

Appending text to text area on click?

JavaScript (jQuery):

$("#content-styling-bar td").click(function() {
  if ($(this).text() == "Bold ") {
    $("#description").append("<b></b>");
  }
});

HTML:

<table id="content-styling-bar">
          <tr>
            <td>
              Bold
            </td>
            <td>
              Italic
            </td>
            <td>
              Underline
            </td>
            <td>
              Main Heading
            </td>
            <td>
              Sub Heading
            </td>
            <td>
              Link
            </td>
            <td>
              Image
            </td>
          </tr>
        </table>

我有这个代码。此代码用于网站的博客管理。这个想法是,当我单击粗体 table 单元格时,jQuery 获取包含在该 table 单元格中的文本,然后脚本确定将哪个标记集附加到文本区域。

我更喜欢比较单元格内的文本的方法,而不是向每个单元格的 onclick 参数添加独特的函数,因为我想让我的代码保持干燥,这将涉及创建一堆功能来做基本相同的事情,或者添加很多不需要的 onclick 属性。

我已经用 elert 验证了我在调用 $(this).text() 时确实得到了文本 "Bold",但它似乎不满足 if 语句。

我的 JavaScript 有什么问题?

$(this).text() 可能包含会破坏您 if condition.so 的空格 我认为问题在于此。使用 $(this).text().trim() 以便清除空格。 PLUNCKER

 $("#content-styling-bar td").click(function() {
  if ($(this).text().trim() == "Bold") {
  $("#description").append("<b>shirin</b>");
 }

I have verified with an elert that I'm indeed getting the text "Bold" when I call $(this).text(), but it doesn't seem to satisfy the if statement.

What is the issue with my JavaScript?

最有可能的空格,例如您要检查的字符串末尾的空格 ("Bold ")。

我根本不会那样做,它很脆弱且重复,你将有一个巨大的 if/else 并且在一个地方更改演示文稿文本可能会破坏你的代码别处。相反,我会使用 data-* 属性:

HTML:

<table id="content-styling-bar">
  <tr>
    <td data-tag="b">
      Bold
    </td>
    <td data-tag="i">
      Italic
    </td>
    <!-- ... -->
  </tr>
</table>

然后:

$("#content-styling-bar td").click(function() {
    $("#description").append(document.createElement($(this).attr("data-tag")));
});

如果您有更复杂的案例,它仍然会为您提供一些非演示文本的内容来打开,并且它会自动处理常见案例:

$("#content-styling-bar td").click(function() {
    var tag = $(this).attr("data-tag");
    switch (tag) {
        case "img":
            handleImage();
            break;
        case "a":
            handleLink();
            break;
        default: // "b", "i", "u", "h1", "h2", ...
            $("#description").append(document.createElement(tag));
            break;
    }
});