如何在jQuery中动态赋予属性值

时间:2013-06-05 13:51:36

标签: javascript jquery html

我有一个隐藏的字段,如下所示。

<input type="hidden" value="home" name="newdirpath" />
<input type="button" id="btn"/>

如何通过jquery动态地为属性value赋值?

我的Jquery是这样的。

$('#btn').click(function(){
    var text="helloworld"
    /* What shall I given here for inputting the value of variable text into the attribute `value` of input tag */
});

请建议我,因为我是Jquery和html.Thanks的初学者。

6 个答案:

答案 0 :(得分:1)

这将完成工作:

$('#btn').click(function(){
    var text="helloworld";
    $("input[name=newdirpath]").val(text);
});

示例: http://jsfiddle.net/QHGyE/

答案 1 :(得分:1)

$('#btn').click(function(){
    var text="helloworld"
    $('input[name="newdirpath"]').attr("value",text);
});

答案 2 :(得分:0)

为您的隐藏输入提供如下ID:

<input type="hidden" value="home" name="newdirpath" id="newdirpath" />

然后你的jquery变成这样:

$('#newdirpath').val("your value goes here");

答案 3 :(得分:0)

试试这个:

$('#btn').click(function(){
    var text= "helloworld";
    $('input[name="newdirpath"]').val(text);
});

DEMO

答案 4 :(得分:0)

你也可以尝试一下......

$('#btn').click(function(){
    var text= "helloworld";
    $(this).prev().attr('value',text);
});

如果你想要更具体,因为你之前有多个隐藏的输入字段而你只想要定位一个,那么你可以选择通过它的名字属性查找一个隐藏的字段......

$('#btn').click(function(){
    var text= "helloworld";
    $(this).prev('input[name=newdirpath]').attr('value',text);
});

查看我的Fiddle并祝你好运!

答案 5 :(得分:-1)

尝试

<input type="hidden" id="ids" value="home" name="newdirpath" />

$('#ids').val(text);
相关问题