jQuery 如何获取可选jquery元素的innerHTML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18786050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the innerHTML of selectable jquery element?
提问by Tushar Gupta - curioustushar
I have a php generated list whose list items are selectable using jquery selectable widget. The list for all intents and purposes is:
我有一个 php 生成的列表,其列表项可以使用 jquery 可选小部件进行选择。所有意图和目的的列表是:
<ul id="#select-image">
<li class="ui-widget-content">Item 1</li>
<li class="ui-widget-content">Item 2</li>
<li class="ui-widget-content">Item 3</li>
<li class="ui-widget-content">Item 4</li>
<li class="ui-widget-content">Item 5</li>
<li class="ui-widget-content">Item 6</li>
<li class="ui-widget-content">Item 7</li>
</ul>
And the jQuery selectable is declared as:
并且 jQuery 可选声明为:
<script>
$(function() {
$("#select-image").selectable({
selected: function( event, ui ) {
var $variable = $('.ui-selected').innerHTML;
console.log($variable);
}
});
});
</script>
An event takes place after a list item has been selected, in the example it outputs to the browser console. The output however is "undefined." The selector $('.ui-selected').is correct as it shows as an object in the browser's console. Where am I going wrong?
选择列表项后会发生一个事件,在示例中它输出到浏览器控制台。然而,输出是“未定义的”。选择器$('.ui-selected').是正确的,因为它在浏览器的控制台中显示为一个对象。我哪里错了?
回答by Tushar Gupta - curioustushar
回答by Ganesh Pandhere
Use .val()instead of .innerHTMLfor getting value of selected option
使用.val()而不是.innerHTML获取所选选项的值
Use .text()for getting text of selected option
使用.text()为获得所选选项的文本
Thanks for correcting :)
谢谢指正:)
回答by Sasidharan
$(function() {
$("#select-image").selectable({
selected: function( event, ui ) {
var $variable = $('.ui-selected').html();
console.log($variable);
}
});
});
or
或者
$(function() {
$("#select-image").selectable({
selected: function( event, ui ) {
var $variable = $('.ui-selected').text();
console.log($variable);
}
});
});
or
或者
$(function() {
$("#select-image").selectable({
selected: function( event, ui ) {
var $variable = $('.ui-selected').val();
console.log($variable);
}
});
});
回答by Arun P Johny
The parameter uihas a property called selectedwhich is a reference to the selected dom element, you can call innerHTMLon that element.
该参数ui有一个名为的属性selected,它是对所选 dom 元素的引用,您可以调用innerHTML该元素。
Your code $('.ui-selected').innerHTMLtries to return the innerHTMLproperty of a jQuery wrapper element for a dom element with class ui-selected
您的代码$('.ui-selected').innerHTML尝试为innerHTML具有 class 的 dom 元素返回jQuery 包装器元素的属性ui-selected
$(function () {
$("#select-image").selectable({
selected: function (event, ui) {
var $variable = ui.selected.innerHTML; // or $(ui.selected).html()
console.log($variable);
}
});
});
Demo: Fiddle
演示:小提琴

