从Element Javascript / Jquery获取价值

时间:2013-12-13 14:00:10

标签: javascript jquery html

给出以下html:

<div class="product">
    <span class="name">Product name</span>
    <span class="price">Product price</span>
</div>

<input type="button" class="button" value="Purchase" onclick="myfunction()" />

<input type="hidden" name="p-name" value="">
<input type="hidden" name="p-price" value="">

我正在尝试在javascript中构建一个函数,该函数从span.namespan.price)获取值并将其添加到输入p-name(输入p-price)。

你怎么能这样做?

显然http://api.jquery.com/val/没有按预期工作。

修改

感谢大家的回答!

我已经纠正了你们在评论中指出的html错误。

4 个答案:

答案 0 :(得分:2)

试试这个:

$('.product span').each(function () {
    var selector = 'input[name=p-' + this.className + ']';
    $(selector).val(this.innerHTML);
});

Fiddle

答案 1 :(得分:1)

您需要一个按钮或其他东西来解雇复制:

<input type="button" id="copy_values" value="Copy the values" />

和你的javascript

$(document).ready(function(){
 $("#copy_values").click(function(){
    //Change the value of the input with name "p-name" to the text of the span with class .name
    $('input[name="p-name"]').val($('.name').text());
    $('input[name="p-price"]').val($('.price').text());
});

});

答案 2 :(得分:1)

对于span,我们使用 text()函数代替 val()
当我们使用输入时使用.val(),当我们在HTML中使用span时使用.text()。
参考链接:http://api.jquery.com/text/

答案 3 :(得分:-1)

单击HIDDEN字段很难。

如果您将输入类型更改为文本,那么在onclick中您可以编写:this.value = document.getElementById('name')。innerHTML; (要使用此功能,您必须为您的名称添加ID)

或者,您可以创建一个单独的按钮,并且可以触发onclick方法。