【问题标题】:Splitting a long phrase into an array将长短语拆分为数组
【发布时间】:2014-06-15 22:20:34
【问题描述】:

我需要用那句话

每年的这个时候,你都会清理你的壁橱,清理架子上的灰尘,整理你的地板。一旦你处理了灰尘和污垢,那么一些数字清洁呢?浏览您的所有文件和计算机似乎是一项艰巨的任务,但我们找到了使该过程相当轻松的方法。

按下按钮后

拆分成一个数组

在每一步迭代该数组

随心所欲地构建 SPAN 元素以及属性

将 SPAN 元素添加到原始 DIV

向 SPAN 元素或 DIV 添加单击处理程序,这会导致 SPAN 上的样式在鼠标悬停时发生更改。

目前为止

function splitString(stringToSplit, separator) {
  var arrayOfStrings = stringToSplit.split(separator);

  print('The original string is: "' + stringToSplit + '"');
  print('The separator is: "' + separator + '"');
  print("The array has " + arrayOfStrings.length + " elements: ");

  for (var i=0; i < arrayOfStrings.length; i++)
    print(arrayOfStrings[i] + " / ");
}

var space = " ";
var comma = ",";

splitString(tempestString, space);
splitString(tempestString);
splitString(monthString, comma);
for (var i=0; i < myArray.length; i++)
{

}
var yourSpan = document.createElement('span');
yourSpan.innerHTML = "Hello";

var yourDiv = document.getElementById('divId');
yourDiv.appendChild(yourSpan);

yourSpan.onmouseover = function () {
    alert("On MouseOver");

}

对于 html 我有

The DIV that will serve as your input (and output) is here, with
        id="transcriptText":</p>
      <div id="transcriptText"> It’s that time of year when you clean out your
        closets, dust off shelves, and spruce up your floors. Once you’ve taken
        care of the dust and dirt, what about some digital cleaning? Going
        through all your files and computers may seem like a daunting task, but
        we found ways to make the process fairly painless.</div>
      <br>
      <div id="divideTranscript" class="button">&nbsp;Transform the
        Transcript!&nbsp; </div>

关于如何移动一个的任何帮助?我已经卡了很长时间了

【问题讨论】:

  • 你的代码出了什么问题?

标签: javascript html arrays button string-split


【解决方案1】:

嗯,首先这看起来像是家庭作业。

也就是说,我会尽量在不提供实际代码的情况下提供帮助,因为我们不应该为家庭作业提供实际可行的解决方案。您将字符串拆分太多次(根据您提供的说明只需要一次),并且您必须将拆分调用的结果实际存储在其他代码可以使用的地方。

您的说明说要向跨度添加属性,但不是哪些属性或其内容应该是什么。

您的函数应遵循说明:

1) 拆分字符串。由于它没有具体说明什么,我假设的话。因此,仅将其拆分为空格,并将标点符号留在原处。

2) 使用从 split() 函数返回的单词数组,像您尝试的那样对其进行迭代,但是 循环范围内的大括号是您要连接 @987654321 的位置@ 原词周围的开始和结束标签。

3) 使用 document.createElement() 将当前 span 变成一个 DOM 元素。将 mouseover 和 click 处理程序附加到它,然后 appendChild() 它到 div。

将处理程序添加到您的按钮以调用上述函数。

请注意,使用 innerHTML() 函数一次插入所有跨度可能更有效,但是您必须再次循环以添加悬停/单击处理程序。

【讨论】:

  • 那么我如何编辑它以拆分整个短语,感谢您的帮助关于这样做。我还要在每个单词之前添加像 span 吗?
  • 分割是按照你已经在做的方式完成的。如果您想在不删除标点符号的情况下拆分每个单词,最直接的方法就是phrase.split(' ')(这是一个空格,表示您正在拆分每个空格)。如果您出于任何原因在单词之间有多个空格(好吧,不会失败,但也会添加到数组空格中),那将失败,尽管这对于您的目的来说似乎没问题。至于class和id;它没有在您的要求中列出,但如果您想添加它们,您可以。
猜你喜欢
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 2012-07-04
  • 1970-01-01
相关资源
最近更新 更多