我改进了psycho brm对jQuery 的filterByData扩展。
在前一个扩展名搜索键-值对的情况下,使用此扩展名,您还可以搜索数据属性的存在,而不管其值如何。
(function ($) {
$.fn.filterByData = function (prop, val) {
var $self = this;
if (typeof val === 'undefined') {
return $self.filter(
function () { return typeof $(this).data(prop) !== 'undefined'; }
);
}
return $self.filter(
function () { return $(this).data(prop) == val; }
);
};
})(window.jQuery);
用法:
$('<b>').data('x', 1).filterByData('x', 1).length // output: 1
$('<b>').data('x', 1).filterByData('x').length // output: 1
// test data
function extractData() {
log('data-prop=val ...... ' + $('div').filterByData('prop', 'val').length);
log('data-prop .......... ' + $('div').filterByData('prop').length);
log('data-random ........ ' + $('div').filterByData('random').length);
log('data-test .......... ' + $('div').filterByData('test').length);
log('data-test=anyval ... ' + $('div').filterByData('test', 'anyval').length);
}
$(document).ready(function() {
$('#b5').data('test', 'anyval');
});
// the actual extension
(function($) {
$.fn.filterByData = function(prop, val) {
var $self = this;
if (typeof val === 'undefined') {
return $self.filter(
function() {
return typeof $(this).data(prop) !== 'undefined';
});
}
return $self.filter(
function() {
return $(this).data(prop) == val;
});
};
})(window.jQuery);
//just to quickly log
function log(txt) {
if (window.console && console.log) {
console.log(txt);
//} else {
// alert('You need a console to check the results');
}
$("#result").append(txt + "<br />");
}
#bPratik {
font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="bPratik">
<h2>Setup</h2>
<div id="b1" data-prop="val">Data added inline :: data-prop="val"</div>
<div id="b2" data-prop="val">Data added inline :: data-prop="val"</div>
<div id="b3" data-prop="diffval">Data added inline :: data-prop="diffval"</div>
<div id="b4" data-test="val">Data added inline :: data-test="val"</div>
<div id="b5">Data will be added via jQuery</div>
<h2>Output</h2>
<div id="result"></div>
<hr />
<button onclick="extractData()">Reveal</button>
</div>
或提琴:http : //jsfiddle.net/PTqmE/46/
.find(el+[data-slide=+current+]);
编写的代码在您的内部吗?看来您错过了一些报价"[data-slide]"