Turn each line of textarea into a link

天涯浪子 提交于 2019-12-25 07:49:33

问题


Let's say for example i have a textarea and a toggle button:

<div class="input">
  <textarea id="links">
    http://facebook.com
    http://friendster.com
    http://google.com
    http://facebook.com
    http://friendster.com
  </textarea>
  <a href="#" class="toggle">Toggle</a>
</div>

How do i make it possible for each link in the textarea to clickable with the click of the toggle button?

$('.toggle').click(function(){
  var clickable = false;
  if(!clickable){
    var links = $(this).closest('.input').find('textarea').val().split('\n');
    $.each(links,function(){
      //lost here
    });
  }
  return false;
});

回答1:


You cannot make clickable links inside textarea, they are for a plain text.

There are possible workarounds though, you can make a div, copy formatted content of textarea to this div, when "Toggle" is clicked, and switch textarea and div.




回答2:


DEMO

Your each function takes index and value parameters that you can use to make your anchors

$.each(links, function (i, val) {
    var newA = $("<a />").text(val).attr("href", $.trim(val));

    $("#links").append(newA).append("<br>");
});

(Though obviously you'll have to add them to a div, as the fiddle does. As anrie says, textareas can only hold text.)



来源:https://stackoverflow.com/questions/8798394/turn-each-line-of-textarea-into-a-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!