使用 JQuery 创建链接的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4261687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to create a link using JQuery?
提问by Marcus Leon
We use jqGrid custom formatters to output links in our JQuery grids. We just construct the links using String manipulation a la:
我们使用 jqGrid 自定义格式化程序在我们的 JQuery 网格中输出链接。我们只是使用字符串操作来构建链接:
var s = "<a title=\"Blah\" href=\"javascript:BlahFunc('" + options.rowId + "')\">This is blah<a>";
Is there a more "clever" way to create links (and other form elements) using JQuery?
有没有更“聪明”的方式来使用 JQuery 创建链接(和其他表单元素)?
采纳答案by Oleg
As Steven Xu correctly mentioned, inserting HTML strings is faster than manipulating the DOM, which is why I'd recommend creating elements with string manipulation instead of jQuery.
正如 Steven Xu 正确提到的那样,插入 HTML 字符串比操作 DOM 更快,这就是为什么我建议使用字符串操作而不是 jQuery 创建元素的原因。
You need only change this:
你只需要改变这个:
var s = "<a title=\"Blah\" href=\"javascript:BlahFunc('" + options.rowId +
"')\">This is blah<a>";
to this:
对此:
var s = "<a title=\"Blah\" href=\"javascript:BlahFunc('" + options.rowId +
"')\">This is blah</a>";
(close <a>
tag with </a>
at the end of the string).
(在字符串末尾关闭<a>
标记</a>
)。
The string manipulation is much faster than the DOM Manipulation (see thisfor example). Moreover the difference will be much more if you try to insert a DOM fragment in the middle of a large HTML code. The usage of DOM DocumentFragmentscan a little improve the performance, but the usage of the string concatenation is the fastest way.
字符串操作比 DOM Manipulation 快得多(参见这个例子)。此外,如果您尝试在大型 HTML 代码中间插入 DOM 片段,则差异会更大。使用DOM DocumentFragments可以稍微提高性能,但使用字符串连接是最快的方式。
All other answers wrote his answer without the knowledge about the context (jqGrid custom formatter) where you use it. I try to explain why it is important in your case.
所有其他答案在不了解您使用它的上下文(jqGrid 自定义格式化程序)的情况下写下了他的答案。我试图解释为什么它对你的情况很重要。
Because of performance advantages, jqGrid builds HTML code fragments for the grid first as the array of strings, then build one string from the string array with respect of .join('')
and insert the result in the table body at the end of all only. (I suppose that you use gridview:truejqGrid option which is almost always recommended). The jqGrid custom formatteris a callback function used by jqGrid during the building of the grid (table) body. The custom formatter must return the HTML code fragment as the stringas the result. The string will be concatenated with other strings which build the body of the grid (table).
由于性能优势,jqGrid首先将网格的HTML代码片段构建为字符串数组,然后从字符串数组中构建一个字符串.join('')
并将结果插入到表体的最后。(我想您使用几乎总是推荐的gridview:truejqGrid 选项)。所述的jqGrid自定义格式是电网(表)主体的建筑过程中使用的jqGrid的回调函数。自定义格式化程序必须以字符串形式返回 HTML 代码片段作为结果。该字符串将与构建网格(表格)主体的其他字符串连接在一起。
So if you will change your current code from pure string manipulation to the jQuery DOM manipulation and converting the results to the string (which needed be returned as the result of the custom formatting) then your code will work slowly and you will have no other advantages*.
因此,如果您将当前代码从纯字符串操作更改为 jQuery DOM 操作并将结果转换为字符串(需要作为自定义格式的结果返回),那么您的代码将运行缓慢,您将没有其他优势*.
The only real disadvantage of the usage of the string manipulations is the problem of the verification of the code which you build. For example, the usage of code without the close tags </a>
is a potential problem which you can have. In the most cases the problem will be solved during the inserting of the DOM fragment, but sometimes you can receive real problems. So you should just test the code which you inserted very carefully.
使用字符串操作的唯一真正缺点是验证您构建的代码的问题。例如,使用没有关闭标签的代码</a>
是一个潜在的问题。在大多数情况下,问题会在插入 DOM 片段的过程中得到解决,但有时您会收到真正的问题。所以你应该非常仔细地测试你插入的代码。
One more remark: If you want to follow unobtrusive JavaScript styleyou can use "#" as the value for the href
attribute and bind the corresponding click
event inside of gridComplete
or loadComplete
event handler. If you will have problems with the implementation of this you can open a new question and I will try to write the corresponding code example for you.
再说一句:如果你想遵循不显眼的 JavaScript 风格,你可以使用“#”作为href
属性的值,并click
在gridComplete
或loadComplete
事件处理程序中绑定相应的事件。如果您在实现这个时遇到问题,您可以打开一个新问题,我会尝试为您编写相应的代码示例。
Note: I think the best implementation way will be the usage of onCellSelect
or beforeSelectRow
instead of binding click
event to every <a>
element in the column. I recommend to read the following answers for details: this one, another oneand one more old answer.
注意:我认为最好的实现方式是使用onCellSelect
或beforeSelectRow
代替将click
事件绑定到<a>
列中的每个元素。我建议阅读以下答案以获取详细信息:this one, another oneand one more old answer。
回答by Gabriele Petrioli
I find the best to be
我发现最好的
$('<a>',{
text: 'This is blah',
title: 'Blah',
href: '#',
click: function(){ BlahFunc( options.rowId );return false;}
}).appendTo('body');
Live exampleat http://www.jsfiddle.net/gaby/RhWgf/
活生生的例子在http://www.jsfiddle.net/gaby/RhWgf/
I have replaced the inline javascript with an attached handler
我已经用附加的处理程序替换了内联 javascript
Quote from the docs about jQuery()
引用来自关于jQuery()的文档
jQuery( html, props)
htmlA string defining a single, standalone, HTMLelement (e.g.
<div/>
or<div></div>
).
propsAn map of attributes, events, and methods to call on the newly-created element.
jQuery( html, props)
html定义单个、独立的HTML元素(例如
<div/>
或<div></div>
)的字符串 。
props在新创建的元素上调用的属性、事件和方法的映射。
Update
更新
If you want the actual text of the link you should wrap it in a div and return the .html()
of that.
如果你想要链接的实际文本,你应该将它包装在一个 div 中并返回.html()
它的。
(alternatively: you can use access the .outerHTML
property of the raw element)
(或者:您可以使用访问.outerHTML
原始元素的属性)
Full exampleat http://www.jsfiddle.net/gaby/RhWgf/1/(removed the click handler, as it would get lost in a string version, and replaced it with a live
handler that targets the specific kind of links)
完整的例子在http://www.jsfiddle.net/gaby/RhWgf/1/(删除单击处理程序,因为它会迷失在一个字符串的版本,并用它代替live
处理程序,目标特定种类的链接)
回答by shoebox639
jQuery('<a>').attr('href', 'url').text('blah')
Will make a jquery object and you can then just add it to the dom with .append
.
将创建一个 jquery 对象,然后您可以将其添加到 dom 中.append
。
回答by TJB
My preferred way is this:
我的首选方式是这样的:
$("<a>", {
title: "Blah",
href: "javascript:BlahFunc('" + options.rowId + "')"
}).append( "This is blah" );
There's good information in this article:
http://marcgrabanski.com/articles/building-html-in-jquery-and-javascript
这篇文章中有很好的信息:http:
//marcgrabanski.com/articles/building-html-in-jquery-and-javascript
回答by Steven
In general, inserting an HTML string is faster and multiple DOM injections and DOM manipulations, which is what this jQuery DOM manipulation amounts to. If you wanted to insert 500 of these, the best option, performance-wise, would be to prepare the HTML string and then append the HTML.
一般来说,插入一个 HTML 字符串会更快,并且会进行多次 DOM 注入和 DOM 操作,这就是这个 jQuery DOM 操作的意义所在。如果您想插入其中的 500 个,最好的选择是在性能方面准备 HTML 字符串,然后附加 HTML。
But for your simple purposes, you current option will suit you just fine. For cleverer, you might use jQuery's DOM manipulation library on your new elements. The below example should be self-explanatory, but if I haven't been clear in a particular are, leave a comment, and I'll help you out.
但出于您的简单目的,您当前的选择将非常适合您。为了更聪明,您可以在新元素上使用 jQuery 的 DOM 操作库。下面的例子应该是不言自明的,但如果我在某个特定的领域没有说清楚,请发表评论,我会帮助你。
var toBeAdded = [
{ title: "one", row: 1, content: "ONE" },
{ title: "two", row: 2, content: "TWO" },
{ title: "three", row: 3, content: "THREE" }
];
var s = toBeAdded.length;
for(i=0;i<s;i++) {
var a = $('<a>');
a.attr('title', toBeAdded[i].title);
a.attr('rel', toBeAdded[i].row);
a.text(toBeAdded[i].content);
a.addClass('blah_class');
a.appendTo($('body'));
}
And then in your universal script:
然后在你的通用脚本中:
$('a.blah_class').live('click', function(){
var rel = $(this).attr('rel');
BlahFunc(rel);
});