[英]How to target a link using jquery that has a unique class name?
<a href="" class="link unique-lightbox-docid(12345)">Download File</a>
First, I want to target links that only have this class identifier: unique-lightbox-id()' into a jquery click action. 首先,我希望将仅具有此类标识符的链接定位到jquery click动作中:unique-lightbox-id()'。
Second, I want it to grab the id inside the open/close parenthesis. 其次,我希望它抓住打开/关闭括号内的id。
Do I need to use regex to accomplish this? 我需要使用正则表达式来完成此操作吗?
Don't include the ID as part of the class. 请勿将ID包含在课程中。 Use a
data
attribute as that's what they are for. 使用
data
属性,因为这就是它们的作用。 Then grab that property instead while matching on a class like normal. 然后,在与普通类匹配时获取该属性。
$('.link').click(function (e) { e.preventDefault(); var id = $(this).data('docid'); alert(id); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="" class="link" data-docid="doc1">Download File 1</a><br /> <a href="" class="link" data-docid="doc2">Download File 2</a><br /> <a href="" class="link" data-docid="doc3">Download File 3</a><br />
Try utilizing Attribute Contains Selector [name*="value"]
String.prototype.match()
with parameter RegExp
/\\(.*\\)/
, String.prototype.slice()
with parameter 1, -1
尝试使用带有参数
RegExp
/\\(.*\\)/
String.prototype.slice()
和带有参数1, -1
String.prototype.slice()
Attribute Contains Selector [name*="value"]
String.prototype.match()
$("a[class*=unique]").on("click", function(e) { e.preventDefault(); var res = e.target.className.match(/\\(.*\\)/)[0].slice(1, -1); // do stuff with `res` $("body").append("<br>" + res); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <a href="" class="link unique-lightbox-docid(12345)">Download File</a>
I would do it this way. 我会这样做。
var partialClassName = 'unique-lightbox-docid';
$('[class*="' + partialClassName + '"]').click(function(e){
var fullClass = $(this).attr('class');
var firstMatchStr = fullClass.substring(fullClass.indexOf(partialClassName), fullClass.length);
var elementId = firstMatchStr.match(/\(.*\)/)[0].slice(1, -1);
$('#' + elementId).html('This is element with id ' + elementId);
e.preventDefault();
});
If you have a class like class="classname(abc) classname2(xyz) unique-lightbox-docid(12345)"
the above way will make sure your're starting at unique-lightbox-docid so by you returning the 1st occurrence of the regex match you will make sure you always have the correct id. 如果您使用的类为
class="classname(abc) classname2(xyz) unique-lightbox-docid(12345)"
则上述方法将确保您以“ unique-lightbox-docid”开头,因此您将返回第一个出现的正则表达式匹配项将确保您始终具有正确的ID。
For some reason the code formatting isn't coming out correctly with this post but here is a fiddle. 由于某种原因,本文的代码格式无法正确显示,但这是一个小提琴。
http://jsfiddle.net/SeanWessell/9svvha3q/1/ http://jsfiddle.net/SeanWessell/9svvha3q/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.