简体   繁体   English

如何在动态输入上使用GetElementsByClassName()

[英]How to use GetElementsByClassName() on dynamic inputs

i got a little problem i want to query my database so when the user use the autocomplete i can get the stock of that product on another column 'td' called *Exist Act * , Ok now with this new scrip when i moveout of the any textbox it change the value of All of the Exist Act column.Is there a solution so the script just change the value on the same row? 我遇到一个小问题,我想查询我的数据库,以便当用户使用自动完成功能时,我可以在名为* Exist Act *的另一列'td'上获取该产品的库存,现在,当我移出任何文本框更改“所有现有行为”列的值。是否有解决方案,所以脚本只需更改同一行的值? this is my code i have changed the whole script, this one 这是我的代码,我已经更改了整个脚本,这一个

$(document).on("mouseout",".service",function(){//begin event
    var $this=$(this);
    var service = $(this).val();        
    var dataString = 'service='+service;
      $.ajax({
        type: "GET",
        url: "busca.php",
        data: dataString,
        success: function(data) {  

     $('.txtHint').html(data);
     }
      });
       });

insted of this one 对此感兴趣

function showUser(str) { 函数showUser(str){

if (str == "") {
  document.getElementsByClassName("txtHint").innerHTML = "";
  return;
} else {
  if (window.XMLHttpRequest) {

    xmlhttp = new XMLHttpRequest();
  }
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      document.getElementsByClassName("txtHint").innerHTML = xmlhttp.responseText;
    }
  };
  xmlhttp.open("GET", "busca.php?q=" + str, true);
  xmlhttp.send();

}}

HTML 的HTML

 <form action="levantar_pedido2.php" method="post" name="form1" target="cuerpo"> <table class="table table-bordered table-condensed" align="left"> <tr class="Estilo9"> <td width="20" align="center ">-</td> <td width="1" align="left"><strong>Cantidad</strong> </td> <td width="50" align="left"><strong>Exist Act *</strong> </td> <td width="100" align="left"><strong>Descripcion</strong> </td> </tr> <tr> <td align="center"> <input type="checkbox" value="X" name="articulo[]" id="articulo" /> </td> <td> <input name="cantidad[]" id="cantidad" type="text" maxlength="5" size="5" value=""> </td> <td align="center"> <div class="txtHint">*</div> </td> <td align="left"> <input onmouseout="showUser(this.value)" type="text" size="50" id="service" class="service" name="service[]" /> <div align="right" class="suggestions"></div> </td> </tr> </table> <table class="table table-bordered table-condensed" align="center"> <div class="inputs"></div> </table> <br> <A class="btn btn-default" id="adder" href="#">Áñadir otro que no este en la lista</A> <div align="right"> <button class="btn btn-primary btn-lg" type="submit" name="Submit" value="Levantar pedido"> <span class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></span> Levantar pedido</button> </div> </form> 

And this is my js for the dynamic inputs 这是我用于动态输入的js

function addInput() {
    $('.inputs').append(
        '<table " class="table table-bordered table-condensed"  align="left"><tr>'+
        '<td width="20"align="center"><input type="checkbox" value="X" name="articulo[]" id="articulo"/></td> '+
        '<td width="74"> <input name="cantidad[]" id="cantidad" type="text"  maxlength="5" size="5" value="" > </td>'+
        '<td width="50"align="center"><div class="txtHint"> *</div></td>'+
        '<td width="100" align="left"><input onmouseout ="showUser(this.value)" type="text" size="50"   class="service" name="service[]" /></td><div class="suggestions"></div> ' +
        '</tr></table>'
    );

this one is the loop i tried to use 这是我尝试使用的循环

 function showUser(str){

if (str == "") {
    document.getElementsByClassName("txtHint")[0].innerHTML = "";
    return;
} else { 
    if (window.XMLHttpRequest) {

        xmlhttp = new XMLHttpRequest();
    } 
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
           var divs=getElementsByClassName("txtHint");
           for(var x=0;x<divs.length;x++){
            divs[x].innerHTML = xmlhttp.responseText;
        }}
    };
    xmlhttp.open("GET","busca.php?q="+str,true);
    xmlhttp.send();

}}

Sorry for my bad english 对不起,我的英语不好

Ok now with this new scrip when i moveout of the any textbox it change the value of All of the Exist Act column.Is there a solution so the script just change the value on the same row? 现在,当我移出任何文本框时,使用新的脚本将更改All Exist Act列的值。是否有解决方案,因此脚本只需更改同一行的值?

You are doing everything right. 您做对了所有事情。 The only problem is you are using this code 唯一的问题是您正在使用此代码

$('.txtHint').html(data);

in your ajax success method, What this does is it will select all the elements with the class txtHint in the entire table and then change all of them. 在您的ajax成功方法中,这将在整个表中选择所有类为txtHint的元素,然后更改所有元素。 You need to select only this respective row element with the class txtHint So what you can do is traverse to top to find the tr in which this input element is wrapped and then find the txtHint class named element within this tr and change only that. 您只需要选择带有类txtHint相应行元素,因此您可以做的是遍历顶部以找到包装此输入元素的tr ,然后在此tr找到名为element的txtHint类,并仅对其进行更改。 So use the below code 所以用下面的代码

$this.closest('tr').find('.txtHint').html(data);

Since you already have $this this will hold the current input element which triggered the event and then $this.closest('tr') will get you the parent tr in which the input is wrapped, Now trace down to the element with class txtHint inside this tr and then change only that. 由于您已经有了$this它将保存触发事件的当前输入元素,然后$this.closest('tr')将为您提供包装输入的父级tr,现在使用txtHinttxtHint该元素在这个tr里面,然后只改变那个。

If you are using JQuery and all of your elements containers will have the .input class then use $(".input").html() to access the html of the element. 如果使用的是JQuery,并且所有元素容器都将具有.input类,则可以使用$(".input").html()访问元素的html。 Now if you need to use an event on the dynamically created element then that is a different story. 现在,如果您需要在动态创建的元素上使用事件,那么情况就不同了。 First you will have to select the document or an element that already existed when the page first loaded in order for events to fire on the dynamically created element. 首先,您必须选择文档或页面首次加载时已经存在的元素,以便事件在动态创建的元素上触发。 See example Below: 请参见下面的示例:

Example HTML created dynamically: 动态创建的示例HTML:

 <!--pretend this was added using the JQuery append() function-->
  <div class="input">I was added dynamically</div>

JQuery Event: jQuery事件:

 //select the document for example first then the selector
 $(document).on("mouseover",".input",function(){//begin event

          //do something when the event is fired

          //alert the html of element hovered over with an input class
          alert($(this).html());


 });//end event

Update: 更新:

The following code will change only td element in a single row after the mouse leaves the .service class element. 鼠标离开.service类元素后,以下代码将仅在一行中更改td元素。 Replace $('.txtHint').html(data); 替换$('.txtHint').html(data); in your ajax success function with the following code: 在您的ajax成功函数中,使用以下代码:

/* Select the parent element which is a 
  td element and then select the previous
  td element which contains the txtHint class 
  */
  $(this).parent().prev("td").html(data);

First off, I would look over how selectors work in jQuery. 首先,我将研究选择器在jQuery中的工作方式。 Unless necessary, I would by consistent with using only one form of selecting elements (ie either, jQuery or document.getElementBy...). 除非必要,否则我将只使用一种形式的选择元素(即jQuery或document.getElementBy ...)。

The basic selectors from jQuery are: jQuery的基本选择器是:

$("tagName") about equivalent to document.GetElementsByTagName $("tagName")大约等于document.GetElementsByTagName

$(".className") about equivalent to document.GetElementsByClassName $(".className")大约等于document.GetElementsByClassName

$("#id") about equivalent to document.GetElementById $("#id")大约等于document.GetElementById

You should notice that the first two return multiple items and only the last returns a single element (the first found with that id). 您应注意,前两个返回多个项目,仅最后一个返回单个元素(第一个找到的具有该ID的元素)。

document.getElementsByClassName("txtHint").innerHTML = "";

Is not valid since you get a NodeList and trying to set the innerHTML. 无效,因为您获得了NodeList并尝试设置innerHTML。 jQuery lets you get away with this since it will run/set most things for the whole list of returned items. jQuery可以让您摆脱困境,因为它将为返回的项的整个列表运行/设置大多数东西。

$('.inputs').append(..)

Tries to find all the elements with class="inputs" and append HTML to them. 尝试查找所有带有class="inputs"的元素,并将HTML附加到它们之后。 In your case you probably want a specific id for the input, so $("#service").append() 在您的情况下,您可能需要输入一个特定的ID,因此$("#service").append()

Depending on the project it may be cleaner to pass the element to whichever function needs to append to the element. 根据项目的不同,将元素传递给需要附加到元素的任何函数可能会更干净。

onmouseout="showUser(this)" and then use this in the function onmouseout="showUser(this)" ,然后在函数中使用this

function showUser(element) {
var str = element.value;
....
$(element).append(...);
}}

But that depends entirely on what you are trying to achieve and the methods purpose. 但这完全取决于您要实现的目标和方法的目的。

All the jQuery Selectors are on their website: http://api.jquery.com/category/selectors/ Search of what you need. 所有jQuery选择器都在其网站上: http : //api.jquery.com/category/selectors/搜索所需内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM