gpt4 book ai didi

javascript - 如何获取 radio oncheck 上特定 div 的源代码?

转载 作者:行者123 更新时间:2023-12-03 04:15:18 26 4
gpt4 key购买 nike

我想获取 div 的源代码,例如,如果 div 包含一些标签,我想获取它们,因为它们是 html 格式,并在文本字段上更新它。

JsFiddle:https://jsfiddle.net/Lindow/g1sp1ms3/2/

HTML:

<form>

<label class="tp_box_1">
<input type="radio" name="selected_layout" class="selected_layout" value="layout_1">
<div class="box_1">
<h3>box_one</h3>
<p>1</p>
</div>
</label>

<br><hr><br>

<label class="tp_box_2">
<input type="radio" name="selected_layout" class="selected_layout" value="layout_2">
<div class="box_2">
<h3>box_two</h3>
<p>2</p>
</div>
</label>

<textarea id="mytextarea"></textarea>
<input id="submit_form" type="button" value="Send">
</form>

JavaScript:

$('input[type="radio"][name="selected_layout"]').change(function() {
if(this.checked) {
// get the specific div children of $this
var selected_layout = $(this).find('.selected_layout');

// get source code of what's inside the selected_layout
/* example :
<h3>box_two</h3>
<p>2</p>
and put it in someVariable.
*/

// and put in into textarea (all this need to happens when a radio is changed with the source code of the checked div)
var someVariable = ...
$('textarea').val(someVariable);
}
});

我怎样才能实现这个目标?如何获取特定 div 内的源代码?

最佳答案

首先,您不希望 selected_layout 等于:$(this).find('.selected_layout') 因为 this > 已经指向该元素。您希望它指向它后面的下一个元素。

我认为这就是您正在寻找的:

$('input[type="radio"][name="selected_layout"]').change(function() {
if(this.checked) {
// get the index within the set of radio buttons for the radio button that was clicked
var idx = $("[type=radio][class=selected_layout]").index(this);

// Get the div structure that corresponds to the same index
var test = $("[class^='box_']")[idx];

// Now, just make that the value of the textarea
$('textarea').val(test.innerHTML);
}
});
textarea { width:100%; height:75px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>

<label class="tp_box_1">
<input type="radio" name="selected_layout" id="sl1" class="selected_layout" value="layout_1">
<div class="box_1">
<h3>box_one</h3>
<p>1</p>
</div>
</label>
<label class="tp_box_2">
<input type="radio" name="selected_layout" id="sl2" class="selected_layout" value="layout_2">
<div class="box_2">
<h3>box_two</h3>
<p>2</p>
</div>
</label>

<textarea id="mytextarea"></textarea>
<input id="submit_form" type="button" value="Send">
</form>

关于javascript - 如何获取 radio oncheck 上特定 div 的源代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44167585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com