从元素Javascript/Jquery获取值

从元素Javascript/Jquery获取值,javascript,jquery,html,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()" />

给定以下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.name
span.price
)获取值,并将其添加到input p-name(input p-price)中

你怎么能做到

显然,它没有按预期工作

编辑

谢谢大家的回答

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

试试这个:

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

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

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

对于span,我们使用text()函数而不是val()函数
在HTML中使用输入时使用.val(),在使用span时使用.text()

参考链接:

很难点击隐藏字段

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


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

您尝试过什么jQuery?您有一个隐藏的输入字段,带有onclick,它永远不会激发。
span
不会为
.val()
返回任何内容,因为它没有
值。使用
.text()
.html()
代替。如何单击不可见的东西?@Milanzor可能他有一个隐藏的鼠标。你想过吗?呃?text()不是一个属性,而是一个函数。和val()可以用于许多其他元素,而不是input.ya。。。我这边的打印错误:)这是HTML中与一起使用的函数。不过您应该提到对
classList
的支持@ᾠῗᵲᄐᶌ 符合事实的更改为
className
$(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());
});