仅对具有特定文本的 href 进行逻辑 - jQuery
我在动态生成的网页上有几个 a 标签,它们就像
<a href='JavaScript:SWESubmitForm(document.SWEForm9_0,s_12,"s_9_1_35_1","1-3ZR4-1743")' tabindex=997 id='s_9_1_35_1'>Add</a>
<a href='JavaScript:SWESubmitForm(document.SWEForm9_0,s_13,"s_9_1_36_1","1-3ZR4-1743")' tabindex=997 id='s_9_1_36_1'>Cancel</a>
上面提到的其他几个标签一样。单击带有文本“添加”的链接时,我需要执行一些逻辑。我知道其中一种方法是将点击事件附加到标签,然后检查文本。
$('a[href*="SWESubmitForm"]').click(function(){
if($(this).text() == "Add"){
//do something
}
但我不确定这是否是最有效的方法。
你们能建议正确的方法吗?
I have several a tags on a dynamically generated web page and they are like this
<a href='JavaScript:SWESubmitForm(document.SWEForm9_0,s_12,"s_9_1_35_1","1-3ZR4-1743")' tabindex=997 id='s_9_1_35_1'>Add</a>
<a href='JavaScript:SWESubmitForm(document.SWEForm9_0,s_13,"s_9_1_36_1","1-3ZR4-1743")' tabindex=997 id='s_9_1_36_1'>Cancel</a>
several others like mentioned above. I need to execute some logic when link with text 'Add' is clicked. I know one of the way is to attach click event to a tags and then check for text.
$('a[href*="SWESubmitForm"]').click(function(){
if($(this).text() == "Add"){
//do something
}
but I am not sure if this is most efficient way to do this.
Can you guys please suggest the right way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的代码可以工作,但是括号有问题。我在 jsfiddle 上测试过
Your code works but you have problems with brackets.I tested on jsfiddle
您可以使用 filter 来实现此目的。
正如您在另一个答案中发布的那样,您想知道这是否是“正确的方式” - 我会说不。正确的方法当然是为每个链接分配一个类,然后使用类选择器将单击事件绑定到它们。但我假设您对 html 没有太多控制权。
话虽如此,我会按照下面的建议使用过滤器。这最大限度地减少了绑定事件的数量。如果您想让它更加高效,我会使用
delegate
或on
并绑定到公共父级。这也减少了绑定点击事件的数量。http://jsfiddle.net/mrtsherman/Uypuq/
You could use filter for this.
As you posted in another answer that you wanted to know whether this is 'the right way' - I would say no. The right way would of course be to assign a class to each of these links then use a class selector to bind the click event to them. But I am assuming that you don't have too much control over the html.
That being said I would use filter as I have suggested below. This minimizes the number of events which are bound. If you want to make it even more efficient I would instead make use of
delegate
oron
and bind to a common parent. This reduces the number of bound click events also.http://jsfiddle.net/mrtsherman/Uypuq/
如果链接 ID 是可预测的并且如 HTML 中所示,则可以使用以下内容:
如果您控制 HTML,则可以在所需链接上放置适当的 ID 或类,然后仅使用这些链接上的选择器。这比尝试根据文本过滤所有链接要有效得多。
If the link id is predictable and as shown in your HTML, you can just use this:
If you control the HTML, you can either put an appropriate ID or class on the desired links and just use selectors off those. That is much more efficient than trying to filter all links based on their text.