日期:2014-05-17  浏览次数:20792 次

js 创建动态文本框,onclick如何获取值?
如下代码,button的onclick能获取到button的值,
想要:button onclick的时候能获取文本框的值,该怎么写?


<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>

<script type="text/javascript">
    
    //创建 input 文本框
var test=1
    function CreateInput(){
var obj = document.getElementById("body_note");
nDiv = document.createElement("div");
nDiv.id="showText"+test;
        obj.appendChild(nDiv);
        var input = document.createElement("input"); 
        input.type = "text";
        input.id = "inputText";
        input.value = test;
var input2 = document.createElement("input"); 
        input2.type = "button";
        input2.id = "button"+test;
input3=input2.id
        input2.value = "button"+test;
input2.onclick = function(){testa(this);};  

        document.getElementById("showText"+test).appendChild(input);
document.getElementById("showText"+test).appendChild(input2);
test++;
    }
function testa(t){
alert (t.value)

}
</script>

</head>

<body id="body_note" onload="CreateInput()">
    <input type="button" name="test" id="test" value="add" onclick="CreateInput()" />
</body>

------最佳解决方案--------------------
有一种简单的方法:
感觉 input2.onclick = function(){testa(this);};   这一句有问题。
把它换成input2.onclick = function() {testa(input);};就行了。也就是把this换成input
------其他解决方案--------------------
获取什么文本框的值
------其他解决方案--------------------
引用:
获取什么文本框的值

每一个button获取每一个text的值
------其他解决方案--------------------
定义一个字符串、在点击按钮的时候、让Str = 文本框.setText
------其他解决方案--------------------
试问,当你第一次点击的时候 input里面根本就没有值,你获取什么?
是不是应该添点什么 ,再获取值?   用onblur 可否?
------其他解决方案--------------------
input2.onclick = function(){testa(this);};

换成
input2.onclick = "testa(this)";

试试
------其他解决方案--------------------
引用:
试问,当你第一次点击的时候 input里面根本就没有值,你获取什么?
是不是应该添点什么 ,再获取值?   用onblur 可否?

input有值呀,看效果图

------其他解决方案--------------------
没看清 题   不好意思 就当我没说,老毛病 又犯了 
------其他解决方案--------------------