简体   繁体   English

将html链接添加到文本输入框中?

[英]Add html link into text input box?

I'm trying to add a HTML link to an input box using the following jQuery: 我正在尝试使用以下jQuery将HTML链接添加到输入框:

var E = "<a class='tagged_person' contenteditable='false' href='http://www.google.com'>Click This</a>";
$("input[name='newComment']").val(E);

Which is working, but its literally displaying the <a href... , which is what I wanted backend wise, but on the frontend, I'd like the user to see it as rendered as a HTML <a> link. 这是<a href... ,但实际上显示了<a href... HTML <a>链接。 Just like on Facebook/Twitter you can tag users and then there's a link. 就像在Facebook / Twitter上一样,您可以标记用户,然后有一个链接。

I think you're looking for the JQuery method .append . 我认为您正在寻找JQuery方法.append That lets you pass a string of HTML and have it parsed into the DOM. 这样,您就可以传递HTML字符串并将其解析为DOM。 Check it out here 在这里查看

For example: 例如:

$('#myDiv').append('<a href="www.google.com">Search for it!</a>');

There's also .appendTo() if it suits your aesthetic better. 如果更适合您的审美观,则还有.appendTo()

Edit : If you're trying to literally stick html as the value of a text input, you can't do that. 编辑 :如果您试图将html作为文字输入的值,则不能这样做。 <input type="text"> carry text, and that's it. <input type="text">随身携带文本,仅此而已。 You'd have to make your own input form, or use a JQuery plugin. 您必须制作自己的输入表单,或使用JQuery插件。 Why would you want to have a link in a form input anyway though? 您为什么仍然要在表单输入中添加链接? Sure, you could have the user redirected when clicking the form through different event handlers, but input is for inputting . 当然,当您通过不同的事件处理程序单击表单时,可以使用户重定向,但是输入仅用于输入 If it redirects, then you didn't really want an input in the first place. 如果重定向,那么您实际上根本就不需要输入。

You can use the following code, which when select it will open the link in a new window. 您可以使用以下代码,当选择它时,它将在新窗口中打开链接。

<form action="../">
<select name="myDestination">
    <option value="http://www.website1.com/">Website 1</option>
    <option value="http://www.google.com/">GOOGLE</option>
</select>
<input type="button"
    value="Open in New Window!"
    onclick="ob=this.form.myDestination;window.open(ob.options[ob.selectedIndex].value)">
</form>

Or without the need to press a button: 或无需按下按钮:

<form action="../">
  <select onchange="window.open(this.options[this.selectedIndex].value,'_top')">
    <option value="">Choose a destination...</option>
    <option value="http://www.website1.com/">Website 1</option>
    <option value="http://www.google.com/">GOOGLE</option>
  </select>
</form>

Also created a jsfiddle to demonstrate: jsFiddle 还创建了一个jsfiddle来演示: jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM