문제

Trying to programatically add links inside of a table.

$("#p"+col).append("<a href='#' id='tablep"+col+"' class='ui-link-inherit' onClick='tableSelect('p"+col+"')'></a>");

Note how ...'tableSelect('p"+col+"')'>... is in single quotes, but its parameters also have to be in quotes. So when it runs, it cuts tableSelect( off like so and throws p1) or whatever number it is, elsewhere.

Here's what it looks like in the console:

<a id="tablep1" class="ui-link-inherit" p1')'="" onclick="tableSelect(" href="#"></a>

See what I mean? Anyway, is there a way around this?

도움이 되었습니까?

해결책

There's a much cleaner way to build elements with jQuery:

$("#p"+col).append($("<a>", {
  href: '#',
  id: 'tablep' + col,
  "class": 'ui-link-inherit',
  click: function() { tableSelect('p' + col); }
}));

다른 팁

onclick attributes are a very outdated method of attaching events. As you are using jQuery to insert the HTML, why not use that to bind your events? Try this:

var $a = $("<a href='#' id='tablep" + col + "' class='ui-link-inherit'></a>").click(function() {
    tableSelect(this);
});
$("#p" + col).append($a);

function tableSelect(obj) {
    // do something with the clicked object
}

It's also worth noting that using incremental id or class attributes is a massive pain for maintenance and will hinder future development. A better method is to use classes and DOM traversal to find the specific element required.

You're using jQuery, don't build HTML via string concatenation.

var newAnchor = $('<a>')
    .attr('id', 'tablep' + col)
    .addClass('ui-link-inherit')
    .click(function () {
        tableSelect('p' +col);
    })
    .appendTo($("#p"+col));

You should escape quotes inside string with backslash:

"\"";

'\'';
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top