Change HTML name element using JavaScript

六眼飞鱼酱① 提交于 2020-01-03 17:00:41

问题


On the press of a div (which I made into a button with other code) I would like the following code:

<div id="w1" name='w1-0' onclick="weekclick(id)">1<br /></div>

...for the name to change from name='w1-0' to name='w1-1'

I'm using the following JavaScript:

function weekclick(id) {    
    document.getElementById(id).input.name = "w1-1";
}

When I alert the id's name, it says it is undefined. What do?


回答1:


see code below:

<div id="w1" name='w1-0' onclick="weekclick(id)">1<br /></div>
<div onclick="weekclick('w1');">click me</div>​

<script type="text/javascript">
function weekclick(id) {    
    document.getElementById(id).setAttribute("name","w1-1");
}​
</script>

link to fiddle - http://jsfiddle.net/TH9C2/

(remove the alert line from the fiddle - it is just there to show you that it works)




回答2:


first of all change your call in the html to this user this.id and not just id:

<div id="w1" name='w1-0' onclick="weekclick(this.id)">1<br /></div>

than make your js like this (remove .input and use setAttribute):

function weekclick(id) {    
    document.getElementById(id).setAttribute('name', 'w1-1');
}

EDIT or you you change your call in html to this:

weekclick(this)

and your js function have to be like this:

function weekclick(domElement) {    
    domElement.setAttribute('name', 'w1-1');
}


来源:https://stackoverflow.com/questions/9447439/change-html-name-element-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!