jQuery拆分为HTML标签,即拆分h2标签的每个实例?

我试图找到所有

标签将它们分开并加入它们并围绕它们 。 我很亲密,但卡住了。

  $(document).ready(function() { // finds all h2's within wrapper div grabs the text splits at ? and applies a links around each one var al = $('#wrapper').find('h2').text().split("?").join("?
"); // Add all the split h2's from the variable above al to a div called .text $('.text').html('
    ' + al + '
'); });

这是我从alert(al)输出的:

 Appropriate Media – Why radio?
Can someone come and speak at my church?
Do you distribute radios?
Do you partner with other organisations?
How is Feba funded?
What are your programmes about?
What denomination does Feba belong to?
What happened to the Chrysolite?
What is airtime?
What is Feba's Statement of Faith?
Where are the programmes made?
Where can I find out about the languages & countries you broadcast in?
Where does the name Feba come from?
Who do you broadcast to?
Why do you broadcast on short wave?

好的,此刻我可以将它们拆分为? 因为每个问题以?结尾? ,但我的问题是错过了第一个问题。

所以我的解决方案是将它们拆分为

标签这是可能的还是有更好的选择我尝试了这么多?

如果你需要这样做,那么为什么不使用jQuery用a锚替换每个h2元素,然后添加一个
之后呢?

 $('h2').after('
').replaceWith(function() { return $('
', { href: '#', text: $(this).text() }); });

更好,更清洁,没有尝试用正则表达式解析HTML的麻烦。 或者,如果您需要包含所有h2标记的新ul元素,请使用以下命令:

 var ul = $(' 

此外, ul列表中的anchors和
标签无效 – 为什么不使用li list元素呢?


实际上,完成此处尝试的最佳方法是使用服务器端代码为每个锚点和h2元素生成#hashid 。 但是,如果您想使用客户端Javascript执行此操作,那么这将更好:

 var ul = $(' 

或者,您可以隐藏每个h2元素后面的所有p元素,并仅在单击h2元素时显示它们

 $('.left-col p').hide(); $('.left-col h2').click(function(){ $(this).nextUntil('h2').toggle(); }); 

如果你想要更有趣的东西,也可以使用fadeToggle()slideToggle()函数。

这非常有效,非常感谢。 我只是想了解代码,以便将来可以利用它。 我对jquery很新,想学习;)

这是我正在处理的网页和完整代码,因此您可以看到结果。 你可能会看到更好的方法。

http://www.giveradio.org.uk/faqs