如何创建一个超链接,其 onclick 处理程序是匿名函数?

发布于 2024-10-14 15:13:32 字数 1303 浏览 3 评论 0原文

我正在尝试动态生成 Flexigrid 生成的表格单元格的 onclick 事件处理程序:

// ...
preProcess: function (data) {
    var rows = data.rows;
    for (var i = 0; i < rows.length; ++i) {
        var row = rows[i];
        // If and only if this condition is true, then
        // row.cell[0] must be converted into a hyperlink.
        if (row.cell[1] != '0') {
            // I don't want to use the href attribute, because that would
            // force me to define a non-anonymous function.
            row.cell[0] = '<a href="javascript:void(0)" id="E'
                        + i + '">' + row.cell[0] + '</a>';
            // So I'm going to try assigning the onclick attribute.
            $('#E' + i).click(function () {
                window.open('doc.php?q=' + this.id, 'D' + this.id,
                            'menubar=0,toolbar=0,directories=0,location=0,status=0,' +
                            'resizable=0,scrollbars=0,width=600,height=300');
            });
            $('#E' + i).click().id = row.cell[4];
        }
    }
    return data;
}
// ...

但是,当我单击生成的超链接时,它们不起作用。有什么问题吗?我对闭包的使用? 标记不接受 onclick 属性?


注意:自从我开始使用 jQuery 以来,我的政策是所有函数都应该是匿名函数。请不要建议我使用普通函数。

I am trying to generate dynamically the onclick event handlers of the cells of a flexigrid-generated table:

// ...
preProcess: function (data) {
    var rows = data.rows;
    for (var i = 0; i < rows.length; ++i) {
        var row = rows[i];
        // If and only if this condition is true, then
        // row.cell[0] must be converted into a hyperlink.
        if (row.cell[1] != '0') {
            // I don't want to use the href attribute, because that would
            // force me to define a non-anonymous function.
            row.cell[0] = '<a href="javascript:void(0)" id="E'
                        + i + '">' + row.cell[0] + '</a>';
            // So I'm going to try assigning the onclick attribute.
            $('#E' + i).click(function () {
                window.open('doc.php?q=' + this.id, 'D' + this.id,
                            'menubar=0,toolbar=0,directories=0,location=0,status=0,' +
                            'resizable=0,scrollbars=0,width=600,height=300');
            });
            $('#E' + i).click().id = row.cell[4];
        }
    }
    return data;
}
// ...

However, when I click on the generated hyperlinks, they don't work. What's the problem? My use of closures? The <a> tag doesn't accept the onclick attribute?


NOTE: Since I began using jQuery, my policy is all functions shall be anonymous functions. Please don't suggest me using an ordinary function.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

两个我 2024-10-21 15:13:32

听起来你要找的是 live()

为现在和将来匹配当前选择器的所有元素的事件附加一个处理程序

实际上,它允许您为尚不存在的元素创建事件处理程序。
我感觉您只想对当前代码进行最小的更改才能完成这项工作。在这种情况下, live() 是您最好的选择,因为您的代码只会从 更改

$('#E' + i).click(function () { ...

$('#E' + i).live('click', function () { ...

Sounds like what you're looking for is live():

Attach a handler to the event for all elements which match the current selector, now and in the future

In effect, it allows you to create event handlers for elements that do not exist yet.
I get the feeling you only want to make minimal changes to your current code in order to make this work. In that case, live() is your best option since your code would only change from

$('#E' + i).click(function () { ...

to

$('#E' + i).live('click', function () { ...
三生路 2024-10-21 15:13:32

使用 jQuery(或浏览器的本机 dom 函数)创建元素并附加一个事件处理程序:

$('<a href="#" id="E' + i + '"/>').html(row.cell[0]).click(function(e) {
    e.preventDefault();
    // your code
});

Create the element using jQuery (or the browser's native dom functions) and attach an event handler:

$('<a href="#" id="E' + i + '"/>').html(row.cell[0]).click(function(e) {
    e.preventDefault();
    // your code
});
与他有关 2024-10-21 15:13:32

It looks like you're creating the <a> using raw string concatenation, and then assigning it... where? If the link isn't part of the DOM, then $('linkID') won't find anything, effectively assigning your click handler to nothing. jQuery selectors only search the DOM.

风情万种。 2024-10-21 15:13:32

首先,看起来您没有添加 id='#E' + i 。

所以,我猜当你调用 $('#E' + i) 时,它会返回一个空的 jQuery 对象。您可以通过警告 $('#E' + i).length 来检查这一点。 0 表示未发现任何内容。

其次,您不需要 javascript:void(0) 调用。只需将其替换为“#”并在匿名函数中调用 event.preventDefault() 即可。您还需要将事件作为参数传递给匿名函数。

Firstly, it doesn't look like you're appending your with id='#E' + i.

So, I'd guess that when you call $('#E' + i), it's returning an empty jQuery object. You can check for this by alerting $('#E' + i).length. 0 means nothing was found.

Second, you don't need to the javascript:void(0) call. Just replace it with '#' and call event.preventDefault() in your anonymous function. You'll need to pass event as a parameter to the anonymous function, as well.

夜巴黎 2024-10-21 15:13:32

您正在尝试将 onclick 事件连接到尚不存在的元素上。此时,该元素仅以文本形式存在于数组中,由于代码尚未添加到 DOM,选择器无法找到它。

如果要对事件处理程序使用匿名函数,则必须等待挂接事件,直到创建元素以便它作为对象存在。

You are trying to hook up the onclick event on an element that doesn't exist yet. At the time, the element only exist as text in the array, as the code hasn't been added to the DOM, the selector can't find it.

If you want to use an anonymous function for the event handler, you have to wait to hook up the event until the element has been created so that it exists as an object.

简美 2024-10-21 15:13:32

使用 jQuery 的 live 事件。

为了便于查看发生的情况,我还向链接添加了一个类,因为我假设页面上还有其他链接。

function preProcess(data) {
    ...
    row.cell[0] = '<a href="#" class="clickMe" id="E' + i + '">' + row.cell[0] + '</a>';
}

jQuery("a.clickMe").live("click", function(event) {
    event.preventDefault();
    window.open('doc.php?q=' + this.id, 'D' + this.id, .....
});

免责声明:我从未使用过 flexigrid,但从您的其他评论来看,您似乎可以在 flexigrid 将内容放入 DOM 之前修改内容。

实时事件允许在将元素添加到 DOM 之前连接单个处理程序(匿名或匿名)。

请参阅:jQuery live()

.live()

将处理程序附加到事件
对于所有匹配的元素
当前选择器,现在并且在
未来

Use jQuery's live event.

For ease of seeing what's going on, I'm also adding a class to the link because I'm assuming that there's other links on the page, .

function preProcess(data) {
    ...
    row.cell[0] = '<a href="#" class="clickMe" id="E' + i + '">' + row.cell[0] + '</a>';
}

jQuery("a.clickMe").live("click", function(event) {
    event.preventDefault();
    window.open('doc.php?q=' + this.id, 'D' + this.id, .....
});

Disclaimer: I've never used flexigrid, but from your other comments, it appears you are able to modify the content before flexigrid puts it in the DOM.

The live event lets up hook up a single handler (anonymous or not) before the element is added to the DOM.

See: jQuery live()

.live()

Attach a handler to the event
for all elements which match the
current selector, now and in the
future

秋凉 2024-10-21 15:13:32

我复制了你的代码,经过一些小的修改后,我让它工作了。我假设数据指的是表对象。这是我的代码和虚拟 HTML。

<html>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>   
  </head>
  <body>
    <table id='myTable'>
      <tr>
        <td>x</td><td>1</td><td>a</td><td>f</td><td>p</td>
      </tr>
      <tr>
        <td>y</td><td>2</td><td>b</td><td>g</td><td>q</td>
      </tr>
    </table>
    <script>
      function preProcess(data) {
        var rows = data.rows;
        for (var i = 0; i < rows.length; ++i) {
        var row = rows[i];
        // If and only if this condition is true, then
        // row.cell[0] must be converted into a hyperlink.
        if (row.cells[1] != '0') {
        // I don't want to use the href attribute, because that would
        // force me to define a non-anonymous function.
          row.cells[0].innerHTML = '<a href="javascript:void(0)" id="E' + i + '">' 
                               + row.cells[0].innerHTML + '</a>';
        // So I'm going to try assigning the onclick attribute.
          $('#E' + i).click(function () {
                  window.open('doc.php?q=' + this.id, 'D' + this.id,
                    'menubar=0,toolbar=0,directories=0,location=0,status=0,' +
                    'resizable=0,scrollbars=0,width=600,height=300');
          });
          //$('#' + id).click().id = row.cells[4];
          }
        }
        return data;
      }  

      $(document).ready(function() {
        preProcess(document.getElementById('myTable'));
      });

    </script>
  </body>
</html>

我的更正如下(我认为有些可能是由于您复制帖子代码时的转录所致):

  1. 我用单元格替换了单元格
  2. 我在单元格索引后添加了innerHTML
  3. 我将链接设置为 javascript:void 而不是 javascript.void
  4. 我注释掉了 $('#' + id).click().id = row.cells[4]; 行,因为我不知道它做了什么。

有了这些改变,它就像一种魅力。

我希望这有帮助。

I copied your code and, after a few minor corrections, I made it work. I assumed that data was referring to a table object. Here's my code together with dummy HTML.

<html>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>   
  </head>
  <body>
    <table id='myTable'>
      <tr>
        <td>x</td><td>1</td><td>a</td><td>f</td><td>p</td>
      </tr>
      <tr>
        <td>y</td><td>2</td><td>b</td><td>g</td><td>q</td>
      </tr>
    </table>
    <script>
      function preProcess(data) {
        var rows = data.rows;
        for (var i = 0; i < rows.length; ++i) {
        var row = rows[i];
        // If and only if this condition is true, then
        // row.cell[0] must be converted into a hyperlink.
        if (row.cells[1] != '0') {
        // I don't want to use the href attribute, because that would
        // force me to define a non-anonymous function.
          row.cells[0].innerHTML = '<a href="javascript:void(0)" id="E' + i + '">' 
                               + row.cells[0].innerHTML + '</a>';
        // So I'm going to try assigning the onclick attribute.
          $('#E' + i).click(function () {
                  window.open('doc.php?q=' + this.id, 'D' + this.id,
                    'menubar=0,toolbar=0,directories=0,location=0,status=0,' +
                    'resizable=0,scrollbars=0,width=600,height=300');
          });
          //$('#' + id).click().id = row.cells[4];
          }
        }
        return data;
      }  

      $(document).ready(function() {
        preProcess(document.getElementById('myTable'));
      });

    </script>
  </body>
</html>

My corrections were the following (I think some might be due to transcription when you were copying the code for the post):

  1. I replaced cell with cells
  2. I added innerHTML after the cell index
  3. I set the link to javascript:void instead of javascript.void
  4. I commented out the line $('#' + id).click().id = row.cells[4];, because I had no idea what it did.

With those changes it worked like a charm.

I hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文