简体   繁体   English

如何替换名称属性

[英]How can I replace the name attribute

I have this PHP output:我有这个 PHP output:

$total.":".$newId;

When success the function live_update() echo response back.成功时 function live_update() 回显响应。 I need to split PHP output into $total & $newId and change the existing input name attribute to the $newId.我需要将 PHP output 拆分为 $total & $newId 并将现有的输入名称属性更改为 $newId。 To do this, I tried my best for hours but I didn't succeed.为此,我努力了几个小时,但没有成功。 Any help will be highly appreciated.任何帮助将不胜感激。 This is the live_update() function:这是 live_update() function:

<script>
    function live_update(el) {
        var str = el.value ;
        var id  = el.id ;
        var name= el.name;
        
        if (str.length==0) { 
        document.getElementById("live_update").innerHTML="";
        
        return;
      }

      if (window.XMLHttpRequest) 
      {
        xmlhttp=new XMLHttpRequest();
      }
        
      xmlhttp.onreadystatechange=function() {
            var Resp = this.responseText;
            var SplitedId = id.split(".");  
          
            if(SplitedId[1] == "di")
            {
                var Fres = Resp.split(":");
                document.getElementsByName(name).name=Fres[1];
                var Total = Fres[0];
            }else{
                var Total = Resp;
            }
          
        
    if (this.readyState==4 && this.status==200) {
        document.getElementById("live_update").innerHTML=Total;
        document.getElementsByName("coupon_row").style.disabled='none';
        
     }
    }
      
      xmlhttp.open("GET","profiles.php?act=live_update&u_key={u_key}&name="+name+"&id="+id+"&q="+str,true);
      xmlhttp.send();
    }
</script>

Change改变

document.getElementsByName(name).name=Fres[1];

to

document.getElementsByName(name)[0].setAttribute('name', Fres[1]);

guessing that you want a way to change name of a single element.猜测您想要一种更改单个元素名称的方法。 you can do as above.你可以像上面那样做。

if there are multiple elements with same name, simply iterate and change name with如果有多个具有相同名称的元素,只需迭代并更改名称

el.setAttribute('name', Fres[1])

Hope it works!希望它有效!

You should use the setAttribute() method to set a name to a HTML element.您应该使用setAttribute()方法将名称设置为 HTML 元素。 So, this is how it goes,所以,事情是这样的,

document.getElementsByName(name)[0].setAttribute("name", Fres[1]);

And document.getElementsByName() returns a list of elements so since you need the first element gotta use [0] index and set the name as shown.并且document.getElementsByName()返回一个元素列表,因此由于您需要第一个元素,因此必须使用[0]索引并如图所示设置名称。
If you want to update the same element you passed in live_update(el) you can simply do this如果您想更新您在live_update(el)中传递的相同元素,您可以简单地执行此操作

el.setAttribute("name", Fres[1]);

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

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