「content」という変数にHTMLの文字列が含まれています。HTMLの文字列には、IDを持つスパンが含まれています。例:
<span id="valuespan">This is the value of a text box</span>
スパンタグの間に含まれているものをチェックボックスの値として使用したいのですが、これを行う方法がよくわかりません。
誰かが私を助けることができますか?
ありがとう!
文字列はまだ文字列であり、ページ上の要素ではないため、山かっこを正規表現と一致させるか、jQueryを使用して要素を作成してソースを抽出することができます
RegExp
var content = '<span id="valuespan">This is the value of a text box</span>';
var text = content.match(/>(.*)<\/span>/)[1];
$(target-checkbox).val(text);
jQuery
var content = '<span id="valuespan">This is the value of a text box</span>';
var text = $(content).text();
$(target-checkbox).val(text);
正規表現はひどいので、可能な限り避ける必要がありますが、これはjQueryの恐ろしい使用法でもあります。可能であれば、おそらく情報チェーンをさらに振り返り、テキストを別の方法で処理する必要があります。
コメント用に編集:一意のIDを使用した複数のスパン用
var content = '<span id="valuespan1">This is the value of a text box</span><span id="valuespan2">This is the value of a text box</span>';
var fragment = $('<div />').html(content);
var text1 = fragment.find('#valuespan1').text();
var text2 = fragment.find('#valuespan2').text();
チェックボックスを動的に作成するための答えは次のとおりです: http://jsfiddle.net/martinschaer/zQAHj/
var span = '<span id="valuespan">This is the value of a text box</span>';
var value = $(span).text();
var id = $(span).attr('id');
var field = '<input type="checkbox" name="' + id + '" id="' + id + '" value="' + value + '" />';
field += '<label for="' + id + '">' + value + '</label>';
$('#theform ul').append('<li>' + field + '</li>');
変数内の複数のスパンの場合:http: //jsfiddle.net/martinschaer/2b5Lj/
var span = '<span id="valuespan">This is the value of a text box</span><span id="valuespan2">This another text box value</span>';
$('span', $('<div>' + span + '</div>')).each(function(){
var value = $(this).text();
var id = $(this).attr('id');
var field = '<input type="checkbox" name="' + id + '" id="' + id + '" value="' + value + '" />';
field += '<label for="' + id + '">' + value + '</label>';
$('#theform ul').append('<li>' + field + '</li>');
});
文字列を取得するには:
var contents = $('#valuespan').text();
チェックボックスに適用するには:
$('#checkbox').val(contents);
これは、スパン文字列がページにないことを前提としています。コンテンツ変数を追加のdivでラップしました。これによりfind
、スパンがどのレベルのhtmlhirarchyであるかに関係なく使用できるようになります。
デモ:http://jsfiddle.net/8WZJT/
var content='<span id="valuespan">This is the value of a text box</span>';
$('#test').val($('<div>').append(content).find('#valuespan').text()).click(function(){
alert($(this).val())
})