2014-03-31 32 views
0

通过jQuery我试图更改隐藏字段的名称值。有很多这些部分HTML元素,所以我试图做这样的,它不会工作使用next更改文本字段的名称值

<section> 
    People: 
    <div data-score-name="people" class="options"> 
     <img src="star-on.png" alt="1" title="bad"> 
     <img src="star-on.png" alt="2" title="poor"> 
     <img src="star-on.png" alt="3" title="regular"> 
     <img src="star-half.png" alt="4" title="good"> 
     <img src="star-off.png" alt="5" title="gorgeous"> 
     <input type="hidden" name="score[]" value="3.5"> 
    </div> 
</section> 

中的JavaScript:

var ScoreName = $(this).attr('data-score-name'); 
$('.options').next().attr('name', 'score[' + ScoreName + ']'); 

我在打字错了?

我正在通过萤火得到的错误是:

TypeError: $(...).next(...).attr(...) is undefined 

更新:我解决了这个由只做

var ScoreName = $(this).attr('data-score-name'); 
    $(this).append("<input type='hidden' name='rate[" + ScoreName + "]' value='" + score + "'>"); 

PS:对不起,如果我是模糊的,无论如何我只是匆忙之中,我会回来更新这个关于评级系统的评论,这样任何其他人都会帮助他们。

+1

你会提交完整的代码吗?这是指什么? – ProllyGeek

+0

本来它的完整代码,我试图做的最终结果是改变 to

+0

代码中存在一些遍历问题...除此之外,它很好http://jsfiddle.net/arunpjohny/MuN7P/1/ –

回答

0

我认为这个jQuery放在一个事件处理程序内?我将演示如何改变这种价值与点击处理程序演示缘故

$('div.options').click(function() { 
    var scoreName = $(this).data('score-name'); // same as .attr('data-score-name'); 
    var newName = 'score[' + ScoreName + ']'; 
    $(this).find('input[name="score[]"]').attr('name', newName); 
}); 

在你说你有很多section元素与这些隐藏场的情况下,你真的需要使用this帮助瞄准正确的输入,因为在你的问题中,你使用类名称作为选择器,所以会有很多可能的结果。

1

至于有没有其他输入字段,你可以像这样访问:

$('.options').next('input').attr('name', 'score[' + ScoreName + ']'); 

或者这样会更好:

$('.options').next('input[name="score[]"').attr('name', 'score[' + ScoreName + ']');