2016-03-05 55 views
2

我想通過動態創建的ID getElementById,但是當我嘗試記錄它,它說未定義。通過動態創建ID getElementById

"<input type='text' class='span2' name='price' pattern='[0-9.]*' id='p'"+ field.id + "placeholder='Price' value='0' />" 

控制檯:

console.log(document.getElementById("p"+field.id).value); 
console.log($("#p"+field.id).val()); 

都表示不確定。我在做什麼錯?

+1

爲什麼你在你的HTML做到這一點? '... id ='p'+ field.id + placeholder ='Price'...''用'placeHolder'連接'filed.id' –

+1

@RajaprabhuAravindasamy試圖說的是,你可能會嘗試添加一個空格'placeholder'以便生成的字符串讀取'... id ='p'「+ field.id +」placeholder' –

回答

2

你串連你的HTML字符串是不正確的方式,

...id='p'"+ field.id.. 

所以上面的代碼會進行評估,以id='p'Something雖然渲染somethingfield.id來將被視爲一個attribute

所以儘量把它寫像,

"<input type='text' class='span2' name='price' pattern='[0-9.]*' id='p"+ field.id + "' placeholder='Price' value='0' />" 
//------------------------------------------------------------------^----------------^ 
//changed the position of quotes. 
+1

謝謝Rajaprabhu –