1

の値を持つボタンがあり、ボタンをクリックすると、IDとtestを持つ要素を操作する JavaScript が実行されます。スクリプトは、2 つの要素 (test1 と test2) を別々に処理できる必要があります。test1test2

一般化されたスクリプトを作成しようとしています (つまり、test の特定の値を使用するのではなく、クリックされているボタンの値は何でも使用します)。そうすれば、ボタンごとに 1000 もの異なるスクリプトを作成する必要がなくなります。対応する名前の要素を持つボタンがある限り、基本的に 1 つのスクリプトが機能します。

これは可能ですか?

4

4 に答える 4

2

要素名(name属性?) が何を意味するのかわかりませんquerySelectorAllが、多くの作業を行うことができます。

document.querySelectorAll('[name^=' + value + ']')

nameの内容で始まる属性を持つすべての要素を選択するために使用できますvalue

http://jsfiddle.net/dDwfd/

他の人が示唆しているように、jQuery は多くの反復処理を内部で処理するため、便利な場合があります。JS コードはもっと単純です: http://jsfiddle.net/dDwfd/1/

于 2013-03-29T23:41:27.157 に答える
0

DOM 操作の最も一般的な環境は、sizzle を使用してセレクターを処理する jQuery です。

それはあなたが探しているもののようです: http://jquery.com/インスピレーションのソースを確認できます。

于 2013-03-29T23:42:32.283 に答える
0

http://jsfiddle.net/xAWUx/1/

HTML:

<button class="action-btn" data-value="test">Test Button</button>
<button class="action-btn" data-value="garage">Test Button</button>

<input name="test1" value="test1">
<input name="test2" value="test2">
<input name="garage1" value="garage1">
<input name="garage2" value="garage2">

jQuery の使用:

function manipulateElement(i, el) {
    var $el = $(el);
    // $el is a jQuery-wrapped element that has a
    // name attribute that starts with the data-value
    // attribute of the clicked button
    console.log($el);
}

$('.action-btn').click(function() {
    var val = $(this).data('value');
    var elementsToManipulate = $('* [name^=' + val + ']');
    elementsToManipulate.each(manipulateElement);
});
于 2013-03-29T23:55:32.517 に答える
0

次のアプローチをお勧めします(いくつかの点で少し過剰に感じます):

Object.prototype.filterSimilar = function(needle, prop, haystack){
    var elems = [],
        reg = new RegExp(needle);
    for (var i = 0, len = haystack.length; i<len; i++){
        if (reg.test(haystack[i].getAttribute(prop))){
            elems.push(haystack[i]);
        }
    }
    return elems;
};

Object.prototype.getSimilar = function(prop){
    var els = document.getElementsByTagName('*'),
        collection = [];
    if (this.length){
        for (var i = 0, len = this.length; i<len; i++){
            collection.push(this[i].filterSimilar(this[i].getAttribute(prop), prop, els));
        }
    }
    else {
        collection.push(this.filterSimilar(this.getAttribute(prop), prop, els));
    }
    return collection[0];
}; 

var similar1 = document.getElementsByTagName('span').getSimilar('id'),
    similar2 = document.getElementById('test').getSimilar('data-name');

console.log(similar1 + '\n' + similar2);

JS フィドルのデモ

ただし、これは Win 7 の Chrome 25 でのみテストされています。

于 2013-03-31T13:27:35.153 に答える