0

This is some jQuery I use to create links out of system-generated comma separated lists and it always works well.

In a very special circumstance I need the script to add an iframe and open the link in it. I've come up with the following but can't get it to work. My question is, is it possible to push the script to work this way? And if so, where am I going wrong?

JQuery

$('.assigns').each(function() {
var obj = $(this),
    assigns = obj.text().split(','),
    i = 0,
    len = assigns.length;
if (obj.text()) {
    for (i; i < len; i++) {
        var assign = assigns[i].replace(/(^\s*)|(\s*$)/g, '');
        if (assign != "") {

            assigns[i] = '<a onclick="$(' <iframe style="width: 100%; height: 5.5em;" scrolling="no" name="frame" src="http://www.example.com"></iframe>').appendTo('#assign_frame');" title="Assign to '+assign+'" class="button_main_build">'+assign+'</a>';
        }
    }
    obj.html(assigns.join(' '));

}

});

The HTML

<div id="assign_frame"></div>

<p class="assigns">Bob Jones, Tom Smith, John Appleseed</p>
James Mathieson
  • 419
  • 2
  • 5
  • 22
  • 1
    Do *not* use HTML string manipulation to do this! Use the DOM. It's there for a reason. – Ry- Aug 07 '12 at 00:50

2 Answers2

1

Since you're using jQuery, you can do it the jQuery way.

var $links = $(); // empty jQuery container

for (i; i < len; i++) { 
  var assign = assigns[i].replace(/(^\s*)|(\s*$)/g, '');
  // Create jQuery link element
  // and attach events upon creation
  // allowing for delegation
  var $link = $('<a/>', {
    'class': 'button_main_build',
    href: '#',
    title: 'Assign to ' + assign,
    text: assign,
    click: function () {
      var $iframe = $('<iframe/>', {
        name: 'frame',
        src: 'http://www.example.com',
        scrolling: 'no',
      })
      $iframe.css({
        width: '100%',
        height: '5.5em'
      })
      .appendTo('#assign_frame')
    }
  });

  if (assign) 
    $links.add($link)
}

obj.append($links)
elclanrs
  • 92,861
  • 21
  • 134
  • 171
0

This is a better way to accomplish your desired goal:

$('.assigns').each(function() {
var obj = $(this),
    assigns = obj.text().split(','),
    len = assigns.length;
if (obj.text()) {
    for (var i=0; i < len; i++) {
        var assign = assigns[i].replace(/(^\s*)|(\s*$)/g, '');
        if (assign != "") {
            obj.append( $('<a title="Assign to ' + assign + '" class="button_main_build">'+assign+'</a>') );
        }
    }
}
});

$(".button_main_build").live('click', function() {   
    $('<iframe style="width: 100%; height: 5.5em;" scrolling="no" name="frame" src="http://www.example.com"></iframe>').appendTo('#assign_frame');
});
Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157