【问题标题】:get value of cloned select获取克隆选择的值
【发布时间】:2013-06-12 07:47:42
【问题描述】:

我想在克隆并执行 onchange 后获取更改时选择的类和值,但它仅返回原始选择的值。请在下面找到我的代码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Clone</title>
</head>

<body>
<div id="input1" class="clonedInput">
    <select id="fields" class="select">
        <option>Test One</option>
        <option>Test Two</option>
        <option>Test Three</option>
        <option>Test Four</option>
    </select>
</div>
<button>Clone</button>
</body>
</html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('button').click(function(){
        var num = $('.clonedInput').length, // how many "duplicatable" input fields we currently have
            newNum  = new Number(num + 1),      // the numeric ID of the new input field being added
            newElem = $('#input' + num).clone().attr('id', 'input' + newNum).fadeIn('slow');
            newElem.find('select#fields').attr('class','select' + newNum).val('');
            $('#input' + num).after(newElem);
        })
    $('select').change(function(){
        var value = $(this).val(),
        classx = $(this).attr('class');
        console.log(value + ' | ' + classx);
        })
    })
</script>

【问题讨论】:

  • 如果选项标签中没有 value 属性,val 函数将不返回任何内容。

标签: jquery select clone onchange


【解决方案1】:

$-operator 在 DOM 中首次出现,它恰好是原始的。

最简单的解决方案是将克隆元素放置在 DOM 结构中的原始元素之前。

你可以使用.before来做到这一点

另一种解决方案是更改克隆的元素 id/name 并通过 id/name 获取值:

("#clonedElement").attr("id","myID");

【讨论】:

  • 答案很简单,在clone函数里面加上true就行了
  • 如果您找到了答案,请回答您自己的问题并将其选中为已接受的答案以便关闭问题或接受现有答案。
【解决方案2】:

修复它的最简单方法是为 jQuery 的 clone() 方法提供 true 参数,以克隆事件的处理程序。另一种方法是为您的事件处理程序命名并手动将其附加到您的克隆节点,或者第三种方法是 to delegate events 使用 jQuery 的 on() method 到您的选择标签):

newElem = $('#input' + num).clone(true);

example 1

... 或 ....

newElem.change(select_change_handler);
$('select').change(select_change_handler);

example 2

...或...

$(document).on('change', 'select', function(e) {

example 3

【讨论】:

    猜你喜欢
    • 2010-10-19
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多