如何使用动态创建的字段?

发布于 2024-09-10 12:51:58 字数 206 浏览 8 评论 0原文

我有网页布局,其中可以包含多个链接。这些链接是使用 AJAX 函数动态创建的。而且工作正常。

但是,我不知道如何使用这些“动态创建的链接”(即,如果单击它们,如何调用某些 JS 或 jQuery 函数)。我猜浏览器无法识别它们,因为它们是在页面加载后创建的。

是否有一些功能可以“重新渲染”我的页面及其上的元素?

Tnx in adv 对你的帮助!

I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.

But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.

Is there some function, that can "re-render" my page and elements on it?

Tnx in adv on your help!

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

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

发布评论

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

评论(7

↘紸啶 2024-09-17 12:51:58

您可以使用 jQuery 提供的以下 2 个方法:

第一个是 .live() 方法,另一个是 .delegate() 方法。

第一个的用法非常简单:

$(document).ready(function() {
    $("#dynamicElement").live("click", function() {
        //do something
    });
}

如您所见,第一个参数是要绑定的事件,第二个参数是处理该事件的函数。它的工作方式并不完全像“重新渲染”。执行此操作的常用方法( $("#dynamicElement").click(...)$("#dynamicElement").bind("click", ...) )的工作原理是,当 DOM 正确加载时,将确定事件的事件处理程序附加到 DOM 元素 ($(document).ready(...) )。现在,显然,这不适用于动态生成的元素,因为它们在 DOM 首次加载时不存在。

.live() 的工作方式是,它不是将通风处理程序附加到 DOM 元素本身,而是将其附加到 document 元素,利用 JS & 的冒泡属性。 DOM(当您单击动态生成的元素并且没有附加事件处理程序时,它会一直查找顶部,直到找到一个)。

听起来很整洁,对吧?但是这个方法有一个小技术问题,正如我所说,它将事件处理程序附加到 DOM 的顶部,因此当您单击该元素时,您的浏览器必须遍历整个 DOM 树,直到找到正确的事件处理程序。顺便说一句,这个过程效率非常低。这里出现了 .delegate() 方法。

让我们假设以下 HTML 结构:

<html>
<head>
...
</head>
<body>
    <div id="links-container">
        <!-- Here's where the dynamically generated content will be -->
    </div>
</body>
</html>

因此,使用 .delegate() 方法,您无需将事件处理程序绑定到 DOM 顶部,而是可以将其附加到父 DOM 元素。一个 DOM 元素,您确信它将位于 DOM 树中动态生成的内容的某个位置。离他们越近,效果就越好。所以,这应该会产生魔力:

$(document).ready(function() {
    $("#links-container").delegate("#dynamicElement", "click", function() {
        //do something
    });
}

这是一个很长的答案,但我喜欢解释它背后的理论哈哈。

编辑:您应该更正您的标记,它是无效的,因为:1) 锚点不允许使用值属性,并且 2) 您不能有 2 个或更多具有相同 ID 的标记。试试这个:

<a class="removeLineItem" id="delete-1">Delete</a> 
<a class="removeLineItem" id="delete-2">Delete</a> 
<a class="removeLineItem" id="delete-3">Delete</a>

并确定哪个锚点被单击

$(document).ready(function() {
    $("#links-container").delegate(".removeLineItem", "click", function() {
        var anchorClicked = $(this).attr("id"),
            valueClicked = anchorClicked.split("-")[1];    
    });
}

使用该代码,您将在anchorClicked 变量中存储单击的链接的id,并在valueClicked 中存储与锚点关联的数字。

You can use the 2 following methods jQuery provides:

The first one, is the .live() method, and the other is the .delegate() method.

The usage of the first one is very simple:

$(document).ready(function() {
    $("#dynamicElement").live("click", function() {
        //do something
    });
}

As you can see, the first argument is the event you want to bind, and the second is a function which handles the event. The way this works is not exactly like a "re-rendering". The common way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a determinate event to the DOM Element when the DOM has properly loaded ($(document).ready(...) ). Now, obviously, this won't work with dynamically generated elements, because they're not present when the DOM first loads.

The way .live() works is, instead of attaching the vent handler to the DOM Element itself, it attaches it with the document element, taking advantage of the bubbling-up property of JS & DOM (When you click the dynamically generated element and no event handler is attached, it keeps looking to the top until it finds one).

Sounds pretty neat, right? But there's a little technical issue with this method, as I said, it attaches the event handler to the top of the DOM, so when you click the element, your browser has to transverse all over the DOM tree, until it finds the proper event handler. Process which is very inefficient, by the way. And here's where appears the .delegate() method.

Let's assume the following HTML estructure:

<html>
<head>
...
</head>
<body>
    <div id="links-container">
        <!-- Here's where the dynamically generated content will be -->
    </div>
</body>
</html>

So, with the .delegate() method, instead of binding the event handler to the top of the DOM, you just could attach it to a parent DOM Element. A DOM Element you're sure it's going to be somewhere up of the dynamically generated content in the DOM Tree. The closer to them, the better this will work. So, this should do the magic:

$(document).ready(function() {
    $("#links-container").delegate("#dynamicElement", "click", function() {
        //do something
    });
}

This was kind of a long answer, but I like to explain the theory behind it haha.

EDIT: You should correct your markup, it's invalid because: 1) The anchors does not allow the use of a value attribute, and 2) You can't have 2 or more tags with the same ID. Try this:

<a class="removeLineItem" id="delete-1">Delete</a> 
<a class="removeLineItem" id="delete-2">Delete</a> 
<a class="removeLineItem" id="delete-3">Delete</a>

And to determine which one of the anchors was clicked

$(document).ready(function() {
    $("#links-container").delegate(".removeLineItem", "click", function() {
        var anchorClicked = $(this).attr("id"),
            valueClicked = anchorClicked.split("-")[1];    
    });
}

With that code, you will have stored in the anchorClicked variable the id of the link clicked, and in the valueClicked the number associated to the anchor.

烦人精 2024-09-17 12:51:58

在页面初始化代码中,您可以像这样设置处理程序:

$(function() {
  $('#myForm input.needsHandler').live('click', function(ev) {
    // .. handle the click event
  });
});

您只需要能够按类或其他方式识别输入元素。

In your page initialization code, you can set up handlers like this:

$(function() {
  $('#myForm input.needsHandler').live('click', function(ev) {
    // .. handle the click event
  });
});

You just need to be able to identify the input elements by class or something.

书信已泛黄 2024-09-17 12:51:58

这些链接是如何动态创建的?您可以使用正确的选择器,因为它们使用相同的类名或驻留在同一个标​​签中,等等。

How are these links dynamically created? You can use use the correct selector, given that they are using the same class name or resides in the same tag, etc.

落在眉间の轻吻 2024-09-17 12:51:58

考虑这里的 html 表单

<form>
  <input type="text" id="id" name="id"/>
  <input type="button" id="check" name="check value="check"/>
</form>

jquery 脚本,

$('#check).click(function()  {
   if($('#id).val() == '') {
      alert('load the data!!!!);
   }
});

单击按钮时脚本检查文本框 id 的值为 null。如果它为空,它将返回一条警报消息......
我想这就是您正在寻找的解决方案......祝

您有美好的一天..

consider the html form

<form>
  <input type="text" id="id" name="id"/>
  <input type="button" id="check" name="check value="check"/>
</form>

jquery script

$('#check).click(function()  {
   if($('#id).val() == '') {
      alert('load the data!!!!);
   }
});

here on clicking the button the script check the value of the textbox id to be null. if its null it will return an alert message....
i thin this is the solution you are looking for.....

have a nice day..

诗酒趁年少 2024-09-17 12:51:58

通常,浏览器会处理响应 HTML 并将其添加到 DOM 树中,但有时,当前定义的事件不起作用,只需在调用 ajax 请求时重新初始化事件即可。

Noramlly , the browser process response HTML and add it to DOM tree , but sometimes , current defined events just not work , simply reinitialize the event when u call the ajax request ..

千仐 2024-09-17 12:51:58

要使用动态创建的元素,您所需要做的就是创建可以用来定位它们的标识符。在 Firebug 控制台或 Chrome 或 IE 的开发人员工具中尝试以下代码。

$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.com">google</a> <a id="l2" href="http://www.yahoo.com">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});

现在,您应该有两个链接,通常是动态创建广告的链接,并且添加了一个 onclick 处理程序来发出警报(我没有阻止默认行为,因此它会导致您离开页面。)

jQuery 的 . live 将允许您自动将处理程序添加到新创建的元素中。

All you need to do to work with dynamically created elements is create identifiers you can locate them with. Try the following code in console of Firebug or the developer tools for Chrome or IE.

$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.com">google</a> <a id="l2" href="http://www.yahoo.com">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});

You should now have two links where the ad normally is that were dynamically created, and than had an onclick handler added to bring up an alert (I didn't block default behaviour, so it will cause you to leave the page.)

jQuery's .live will allow you to automatically add handlers to newly created element.

壹場煙雨 2024-09-17 12:51:58

如果您的链接是通过 AJAX 传入的,您可以在服务器上设置 onclick 属性。只需将链接输出到 AJAX 中,如下所示:

<a href="#" onclick="callYourFunctionHere();return false;">Holy crap I'm a link</a>

return false 确保链接不会重新加载页面。

希望这有帮助!

If your links are coming in via AJAX, you can set the onclick attributes on the server. Just output the links into the AJAX like this:

<a href="#" onclick="callYourFunctionHere();return false;">Holy crap I'm a link</a>

The return false makes sure the link doesn't reload the page.

Hope this helps!

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