Best way to create a link using JQuery?

后端 未结 6 1367
野性不改
野性不改 2020-12-09 03:00

We use jqGrid custom formatters to output links in our JQuery grids. We just construct the links using String manipulation a la:

var s = \"

        
6条回答
  •  执笔经年
    2020-12-09 04:01

    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.

    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.

    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');
      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);
    });
    

提交回复
热议问题