如何在jQuery中动态地给出属性值

How to give attribute value dynamically in jQuery

本文关键字:属性 动态 jQuery      更新时间:2023-09-26

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

<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的初学者。

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

这将完成工作:

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

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

给你的隐藏输入一个像这样的id:

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

然后你的jquery变成这样:

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

试试这个:

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

你也可以试试这个…

$('#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);
});

查看我的小提琴,祝你好运!

try

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

$('#ids').val(text);