2016-10-24 13 views
7

Tôi có hai yếu tố với các thiết lập sau:jQuery chọn dữ liệu thuộc tính với từ khóa chung

<span data-placeholder-class="test-class"></span> 
<span data-placeholder-template="/some/template.hbs"></span> 

Tôi đang sử dụng gạch chân để lặp qua bất kỳ yếu tố có chứa một trong những thuộc tính này và sau đó thực hiện hành động phù hợp khi nó làm.

Hiện này được thực hiện như vậy

_.each($('[data-placeholder-class], [data-placeholder-template]'), function cb(element) { 
    // code goes here 
}) 

Thay vì phải xác định thuộc tính mỗi dữ liệu để lặp qua tôi tự hỏi nếu có một cách tôi có thể chọn tất cả các thuộc tính có chứa một từ khóa thông thường, trong trường hợp này placeholder . ví dụ.

_.each($('[data-placeholder-*]'), function cb(element) { 
    // code goes here 
}) 

Bất kỳ ai biết điều này có thể thực hiện được không?

+1

có thể trùng lặp của [jQuery - Làm thế nào để chọn giá trị theo tên thuộc tính bắt đầu với] (http: // stackoverflow.com/questions/26657398/jquery-how-to-select-value-by-attribute-name-bắt đầu-với) – Andrew

+0

Câu hỏi đó có những gì bạn đang tìm kiếm không? – Andrew

+0

Không hoàn toàn vì tất cả đều yêu cầu bộ chọn bắt đầu phổ biến, ví dụ: ".trượt". Lý tưởng nhất là tôi muốn sử dụng thuộc tính dữ liệu làm bộ chọn duy nhất để tôi không phải thêm lớp tùy chỉnh vào bất kỳ phần tử nào có các thuộc tính này và tôi có thể chọn theo thuộc tính thay vì – woolm110

Trả lời

0
var eles = $('span').filter(function() { 
    for (var attrName in $(this).data()) { 
    if (attrName.indexOf('placeholder') == 0) { 
     return true; 
    } 
    } 

    return false; 
}); 

console.log(eles); 

Tôi hy vọng điều này sẽ giúp bạn :)

1

Bạn có thể lặp lại các attributes của một tập hợp các yếu tố, đẩy yếu tố để một mảng nếu các yếu tố .attributes.name phù hợp với một chuỗi cung cấp biến

var spans = document.querySelectorAll("span"); 
 

 
function filterAttrs(elems, attr, matches = []) { 
 
    for (var elem of elems) { 
 
    for (var attrs of elem.attributes) { 
 
     // alternatively use `.indexOf()` or `RegExp()` 
 
     // to match parts of string of `.name` or `.value` 
 
     // of `.attributes` `NamedNodeMap` 
 
     if (attrs.name.slice(0, attr.length) === attr) { 
 
     matches.push({ 
 
      "element": elem, 
 
      "attr": { 
 
      "name": attrs.name, 
 
      "value": attrs.value 
 
      } 
 
     }) 
 
     } 
 
    } 
 
    } 
 
    return matches 
 
} 
 

 
var matches = filterAttrs(spans, "data-placeholder"); 
 

 
console.log(matches); 
 

 
matches.forEach(function(match) { 
 
    match.element.textContent = "matches:" + JSON.stringify(match.attr); 
 
    match.element.style.color = "green"; 
 
});
<span data-placeholder-class="test-class"></span> 
 
<span data-placeholder-template="/some/template.hbs"></span> 
 
<span data-not-placeholder-template="/some/template.hbs"> 
 
data-not-placeholder-template 
 
</span> 
 
<span data-not-placeholder-template="/some/template.hbs"> 
 
data-not-placeholder-template 
 
</span>

3

Bạn có thể xem xét sử dụng một chức năng riêng biệt tạo ra bạn r selector, vì vậy bạn sẽ không phải gõ bộ chọn đầy đủ (nhưng bạn sẽ phải viết hàm của khóa học).

e.q .:

function getSelector() { 
    return Array.prototype.map.call(arguments, function(key) { 
     return '[data-placeholder-' + key + ']'; 
    }).join(','); 
} 

này sẽ trở lại selector mong muốn của bạn, và làm việc với 1 ... N đối số.

getSelector('class', 'template') 
// returns "[data-placeholder-template],[data-placeholder-class]" 

_.each($(getSelector('class', 'template')), function cb(element) { 
    // code goes here 
}); 
0

MẪU HTML:

<span data-placeholder-class="test-class">test</span> 
<span data-placeholder-template="/some/template.hbs">hahaha</span> 
<span>hahahahaha</span> 
<span data-test="/some/template.hbs">hahahahaha</span> 

JS:

$('span').filter(function(ndx, item){ 
    var data = Object.keys($(item).data())[0]; // gets data name 
    if (data === undefined) { 
     return; 
    } 
    // checks if data starts with placeholder 
    if (~(data.indexOf('placeholder'))) { 
     // do anything to that item here 
     return item; 
    } 
}).css('color', 'green'); 

Fiddle: here

Hope this helps! :)

1

Tôi biết đây là một câu hỏi jquery, nhưng có một cách vani để làm việc đó, nhờ vào các truy vấn XPath:

Chức năng starts-with() XPath sẽ làm chính xác điều đó.

Vì vậy, truy vấn //*[@*[starts-with(name(), 'data-placeholder')]] sẽ cung cấp cho bạn những gì bạn đang làm sau.

quà nào:

'//' + // from root to anywhere in the tree 
    '*' + // any kind of node 
    '[@*' + // with any attribute 
     '[starts-with(name(), "data-placeholder")]' + // which starts with "data-" 
      ']' 

function getElementsByStartOfAttribute(start_of_attr) { 
 
    var query = document.evaluate("//*[@*[starts-with(name(), '" + start_of_attr + "')]]", 
 
    document, null, XPathResult.ANY_TYPE, null); 
 
    var elements = []; 
 
    var el; 
 
    while (el = query.iterateNext()) { 
 
    elements.push(el); 
 
    } 
 
    return elements; 
 
} 
 

 
var placehodlers = getElementsByStartOfAttribute('data-placeholder'); 
 
console.log(placehodlers); 
 
$(placehodlers).css('background', 'green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span data-placeholder-class="test-class">should find me</span> 
 
<span data-placeholder-template="/some/template.hbs">me too</span> 
 
<span data-not-placeholder-template="/some/template.hbs"> 
 
data-not-placeholder-template 
 
</span> 
 
<span data-not-placeholder-template="/some/template.hbs"> 
 
data-not-placeholder-template 
 
</span>

Các vấn đề liên quan