查找最接近的输入以选择动态生成的代码

时间:2015-07-13 10:19:44

标签: javascript jquery

所以我尝试做的是用id championSpell []改变输入值,只要选择下拉菜单中的代码是动态生成的,所以我总是试图获得最近/下一个输入选择。

更新:以下完整代码:

<script src="LeagueNotes/js/jquery.min.js"></script>
<script src="LeagueNotes/js/champions_list.js"></script>
<script src="LeagueNotes/js/jquery.validate.min.js"></script>
<style>
    * { font-family:Arial; }
    h2 { padding:0 0 5px 5px; }
    h2 a { color: #224f99; }
    a { color:#999; text-decoration: none; }
    a:hover { color:#802727; }
    p { padding:0 0 5px 0; }

    input { padding:5px; border:1px solid #999; border-radius:4px; -moz-border-radius:4px; -web-kit-border-radius:4px; -khtml-border-radius:4px; }
</style>

<h2>
    <a href="#" id="addChampion">Add Another Champion</a>
</h2>
<form name="second_form" id="second_form" action="#" method="POST" style="margin: 0;"  >
    <div id="p_scents">
        <p>    
            <label for="p_scnts">
                <input type="text" id="champion[]" size="20" list="champions" value=""  placeholder="Enter Champion's name">
                <datalist id="champions"></datalist>
                <a href="#" id="addGeneral">Add General Change</a><a></a>
                <a href="#" id="addSpell"> Add Spell</a><a></a>

            </label>
        </p>
    </div>
    <br/><input type="submit" value="submit">
</form>
<script>
    for(var key in champions){
                if(champions.hasOwnProperty(key)){
                    $('#champions').append('<option value="' + key + '">');

                }
            }
    var config = {
                      fillAll: true
                    };

                    document.forms["second_form"].oninput = function(e) {
                      var champion = this["champion[]"];

                      //Force into array
                      if (champion[0] === undefined)
                        champion = [this["champion[]"]];

                      var reached = {
                        valid: 0,
                        unique: 0
                      };

                      var inputs = [].map.call(champion, function(n) {
                        return n.value
                      }).filter(function(n) {
                        return n.length
                      });

                      var valid = [].every.call(champion, function(n, i) {
                        n.setCustomValidity("");
                        if (config.fillAll) return (reached.valid = i, champions.hasOwnProperty(n.value));
                        else return n.value ? (
                          reached.valid = i,
                          champions.hasOwnProperty(n.value) > -1
                        ) : true;
                      });

                      var unique = inputs.slice(0).sort().every(function(n, i, a) {
                        reached.unique = inputs.lastIndexOf(n);
                        return n != a[i - 1];
                      });

                      //Check for valid champions
                      if (!valid) {
                        champion[reached.valid].setCustomValidity("This is not a valid champion, please correct this field and resubmit.")
                      }

                      //Check for duplicates
                      if (!unique) {
                        champion[reached.unique].setCustomValidity("This champion has already been entered.")
                      }

                      this.checkValidity();
                    };

    function change(x, dblchamp){
        if(dblchamp===true){
            if(x==="Passive"){x=0;}
            if(x==="Q"){x=1;}
            if(x==="Q2"){x=2;}
            if(x==="W"){x=3;}
            if(x==="W2"){x=4;}
            if(x==="E"){x=5;}
            if(x==="E2"){x=6;}
            if(x==="R"){x=7;}
            if(x==="R2"){x=8;}


        }else if(dblchamp===false){
            if(x==="Passive"){x=0;}
            if(x==="Q"){x=1;}
            if(x==="W"){x=2;}
            if(x==="E"){x=3;}
            if(x==="R"){x=4;}
        }
        console.log(x);
        return x;
    }
    function val(elm) {
        var championsWithExtraSpells = ["Aatrox", "Elise", "Fizz", "Heimerdinger", "Jayce", "Lee Sin", "Nidalee", "Rek'Sai","Twisted Fate"];
        //var championName = $("#change").closest('input').val();
        //var championName =$("#champion\\[\\]").val();
         var championName = $(elm).closest("label").find("input").val();
        //document.getElementById("champion[]").value;
        console.log(championName);

        if($.inArray(championName, championsWithExtraSpells)==-1){
            var existsInArray = false;}
        else{
            var existsInArray = true;}
         var d = $(elm).val();
        // console.log(d);
        //d = document.getElementById("change[]").value;
        var spellname = document.getElementById("championSpell[]");
        var z = champions[""+championName+""][change(d, existsInArray)];
        test =  $(elm).nextAll("input").first().val('test');
        console.log(test);
        //console.log(d+spellname);
        //test.value=champions[""+championName+""][change(d, existsInArray)];

    }

    $(function() {
        var scntDiv = $('#p_scents');
        var i = $('#p_scents label').size() + 1;
        var j =0;
        $('body').on('click', '#addChampion', function() {
            $('<p><a href="#" id="remScnt">Remove</a><br><label for="p_scnts"><input type="text" id="champion[]" size="20" list="champions" name="champion[]" value="" placeholder="Enter Champion\'s name" /><datalist id="champions"></datalist><a href="#" id="addGeneral">Add General Change</a><a href="#" id="addSpell"> Add Spell</a><a></a></label></p>').appendTo(scntDiv);
                i++;
                return false;
        });

        $('body').on('click', '#remScnt', function() { 
                if( i >2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });

         $('body').on('click', '#addGeneral',function() { 
               $(
               '<p><label for="var"><textarea type="text" id="champion[]" size="20" name="GeneralChange[]" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> <a href="#" id="remVar">Remove Change</a></p>').appendTo($(this).next()); 
                j++;
                return false;
        });


        $('body').on('click', '#remVar',function() { 
                        $(this).parent('p').remove();
                return false;
        });

        $('body').on('click', '#addSpell',function() { 
               $(
               '<p><select name="change[]" id="change[]" onchange="val(this)"><option value="Passive">Passive</option><option value="Q" selected>Q</option><option value="W">W</option><option value="E">E</option><option value="R">R</option></select><label for="var"><input type="text" id="championSpell[]" readOnly="true"><br><textarea type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Enter Description" /><select><option value="buff">Buff</option><option value="nerf">Nerf</option><option value="new">New</option><option value="change">Change</option><option value="bugfix">Bugfix</option></select></label> <a href="#" id="addGeneral">Add Change</a> <a href="#" id="remVar">Remove Spell</a></p>').appendTo($(this).next());
                return false;
        });
});
</script>

3 个答案:

答案 0 :(得分:1)

它是select的下一个兄弟,所以使用.next().closest()用于查找与给定选择器匹配的第一个祖先元素

function val(elm) {
  var test = $(elm).next("input");
  console.log(test);
  test.val("test: " + elm.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="change[]" id="change[]" onchange="val(this)">
  <option value="Passive">Passive</option>
  <option value="Q" selected>Q</option>
  <option value="W">W</option>
  <option value="E">E</option>
  <option value="R">R</option>
</select>
<input type="text" id="championSpell[]" readOnly="true">

但最好使用jQuery事件处理程序

jQuery(function() {
  $('select[name="change[]"]').change(function() {
    $(this).next().val('t: ' + this.value);
  }).change(); //the last change value is used to set the initial value on page load
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="change[]" id="change[]" onchange="val(this)">
  <option value="Passive">Passive</option>
  <option value="Q" selected>Q</option>
  <option value="W">W</option>
  <option value="E">E</option>
  <option value="R">R</option>
</select>
<input type="text" id="championSpell[]" readOnly="true">

答案 1 :(得分:1)

使用.next()

var test = $(elm).next("input").val('test');

你的代码

function val(elm) {
    var test = $(elm).next("input").val('test');
 }

答案 2 :(得分:0)

这个取决于你想要的DOM变化的稳健性。

如果您之间可能包含元素,则最佳选项是

  $(elm).nextAll("input").first().val('test');

nextAll()返回元素的所有后续兄弟,与“input”一起使用将仅返回所有后续输入。然后申请first()

如果该层次结构可能发生变化,您可以将DOM上升到具有两个元素的最近容器,然后再次搜索。

e.g。如果它们在两个标准<div class="form-group">容器中(ala a Bootstrap形式):

  $(elm).closest(".form-group").next(".form-group").find("input").first().val('test');

更新

你应该避免使用jQuery的内联事件处理程序。它们不支持jQuery处理程序所做的所有相同功能,并且没有充分的理由将事件注册与事件处理程序分开。

这里有一个实际的例子http://jsfiddle.net/TrueBlueAussie/mo94pv8k/

$('select').change(function () {
    $(this).nextAll("input").first().val($(this).val());
});

说明:

  • 您当前的ID对jQuery使用没有用,因为[]被保留用于指示jQuery选择器中的属性选择。例如,$('#change[]')是一个无效的选择器。