Javascript 在jquery插件中获取初始选择器
早些时候,我得到了一些关于选择器的帮助,但我坚持以下几点 假设你有一个这样的插件Javascript 在jquery插件中获取初始选择器,javascript,jquery,Javascript,Jquery,早些时候,我得到了一些关于选择器的帮助,但我坚持以下几点 假设你有一个这样的插件 $('#box').customplugin(); 如何在插件中将#框作为字符串获取? 我不确定这是否是正确的方法,任何其他的解决方案都是很好的 考虑到#框是一个选择下拉列表 我遇到的问题是如果我使用常规javascript $('#box').val(x); 选择正确的选项值 但是如果我在插件中尝试同样的方法 ..... this.each(function() { var $this = $(this);
$('#box').customplugin();
如何在插件中将#框作为字符串获取?
我不确定这是否是正确的方法,任何其他的解决方案都是很好的
考虑到#框是一个选择下拉列表
我遇到的问题是如果我使用常规javascript
$('#box').val(x);
选择正确的选项值
但是如果我在插件中尝试同样的方法
.....
this.each(function() {
var $this = $(this);
$this.val(x);
最后一段代码实际上什么都没做
我注意到插件中的#框很难定位,因为它是一个对象而不是字符串
任何帮助都将不胜感激
谢谢
编辑::输入我正在使用的代码以便更好地理解
(function($){
$.fn.customSelect = function(options) {
var defaults = {
myClass : 'mySelect'
};
var settings = $.extend({}, defaults, options);
this.each(function() {
// Var
var $this = $(this);
var thisOpts = $('option',$this);
var thisSelected = $this[0].selectedIndex;
var options_clone = '';
$this.hide();
options_clone += '<li rel=""><span>'+thisOpts[thisSelected].text+'</span><ul>'
for (var index in thisOpts) {
//Check to see if option has any text, and that the value is not undefined
if(thisOpts[index].text && thisOpts[index].value != undefined) {
options_clone += '<li rel="' + thisOpts[index].value + '"><span>' + thisOpts[index].text + '</span></li>'
}
}
options_clone += '</ul></li>';
var mySelect = $('<ul class="' + settings.myClass + '">').html(options_clone); //Insert Clone Options into Container UL
$this.after(mySelect); //Insert Clone after Original
var selectWidth = $this.next('ul').find('ul').outerWidth(); //Get width of dropdown before hiding
$this.next('ul').find('ul').hide(); //Hide dropdown portion
$this.next('ul').css('width',selectWidth);
//on click, show dropdown
$this.next('ul').find('span').first().click(function(){
$this.next('ul').find('ul').toggle();
});
//on click, change top value, select hidden form, close dropdown
$this.next('ul').find('ul span').click(function(){
$(this).closest('ul').children().removeClass('selected');
$(this).parent().addClass("selected");
selection = $(this).parent().attr('rel');
selectedText = $(this).text();
$(this).closest('ul').prev().html(selectedText);
$this.val(selection); //This is what i can't get to work
$(this).closest('ul').hide();
});
});
// returns the jQuery object to allow for chainability.
return this;
}
(函数($){
$.fn.customSelect=函数(选项){
var默认值={
myClass:“我的选择”
};
var设置=$.extend({},默认值,选项);
这个。每个(函数(){
//变量
var$this=$(this);
var thisOpts=$('option',$this);
var thisSelected=$this[0]。selectedIndex;
变量选项\u克隆=“”;
$this.hide();
选项_clone+=''+this选择[this selected]。text+''
for(此选项中的var索引){
//检查选项是否有任何文本,以及该值是否未定义
if(thisOpts[index].text&&thisOpts[index].value!=未定义){
选项\u clone+='- ”+thisOpts[index]。文本+'
'
}
}
选项_clone+='
';
var mySelect=$(“”).html(选项);//将克隆选项插入容器ul
$this.after(mySelect);//在原始文件之后插入克隆
var selectWidth=$this.next('ul').find('ul').outerWidth();//隐藏前获取下拉列表的宽度
$this.next('ul').find('ul').hide();//隐藏下拉部分
$this.next('ul').css('width',selectWidth);
//单击后,显示下拉列表
$this.next('ul')。find('span')。first()。单击(函数(){
$this.next('ul').find('ul').toggle();
});
//单击后,更改顶部值,选择隐藏窗体,关闭下拉列表
$this.next('ul')。查找('ul span')。单击(函数(){
$(this).closest('ul').children().removeClass('selected');
$(this.parent().addClass(“选定”);
selection=$(this.parent().attr('rel');
selectedText=$(this.text();
$(this).closest('ul').prev().html(selectedText);
$this.val(选择);//这是我无法工作的
$(this.closest('ul').hide();
});
});
//返回jQuery对象以允许链接性。
归还这个;
}
本页介绍如何获取选择器:
只有一个提示:.selector()在jQuery 1.7中被弃用,在jQuery 1.9中被删除:。
-西蒙·斯坦伯格
对jQuery集合使用.selector
属性
注意:此API已在jQuery 3.0中删除。该属性从来都不是选择器的可靠指示器,可用于获取当前包含在jQuery集合中的元素集(它是属性),因为后续的遍历方法可能已更改了该集合。需要在插件中使用选择器字符串的插件可以要求将其作为方法的参数。例如,“foo”插件可以写成$.fn.foo=function(selector,options){/*插件代码在这里*/};,使用该插件的人可以编写$(“div.bar”).foo(“div.bar”,{dog:“bark”});其中“div.bar”选择器作为.foo()的第一个参数重复
在您的插件中:
$.fn.somePlugin = function() {
alert( this.selector ); // alerts current selector (#box )
var $this = $( this );
// will be undefined since it's a new jQuery collection
// that has not been queried from the DOM.
// In other words, the new jQuery object does not copy .selector
alert( $this.selector );
}
然而,以下这些可能解决了你真正的问题
$.fn.customPlugin = function() {
// .val() already performs an .each internally, most jQuery methods do.
// replace x with real value.
this.val(x);
}
$("#box").customPlugin();
这就是2017年我在插件中获取选择器字符串的方式:
(函数($,窗口,文档,未定义){
$.fn.\u init=$.fn.init
$.fn.init=函数(选择器、上下文、根){
return(typeof selector=='string')?new$.fn.\u init(选择器,上下文,根)。data('selector',选择器):new$.fn.\u init(选择器,上下文,根);
};
$.fn.getSelector=函数(){
返回$(this).data('selector');
};
$.fn.coolPlugin=函数(){
var选择器=$(this.getSelector();
if(selector)console.log(selector);//输出p#粗体文本
}
})(jQuery、窗口、文档);
//调用插件
$(文档).ready(函数(){
$(“p#boldText”).coolPlugin();
});
一些粗体文本
由于对jQuery的.selector
的弃用和删除,我尝试了javascript的DOM节点
,并提出了2017年及以后的解决方案,直到出现了更好的方法
//** Get selector **//
// Set empty variables to work with
var attributes = {}, // Empty object
$selector = ""; // Empty selector
// If exists...
if(this.length) {
// Get each node attribute of the selector (class or id)
$.each(this[0].attributes, function(index, attr) {
// Set the attributes in the empty object
// In the form of name:value
attributes[attr.name] = attr.value;
});
}
// If both class and id exists in object
if (attributes.class && attributes.id){
// Set the selector to the id value to avoid issues with multiple classes
$selector = "#" + attributes.id
}
// If class exists in object
else if (attributes.class){
// Set the selector to the class value
$selector = "." + attributes.class
}
// If id exists in object
else if (attributes.id){
// Set the selector to the id value
$selector = "#" + attributes.id
}
// Output
// console.log($selector);
// e.g: .example #example
所以现在我们可以将其用于任何目的。您可以将其用作jQuery选择器…例如,$($selector)
编辑:我的原始答案只会获取元素上第一个出现的属性。因此,如果我们想要获取元素上类之后的id,它将不起作用
我的新解决方案使用一个对象来存储属性信息,因此我们可以检查是否同时存在或仅存在一个,并相应地设置所需的选择器。感谢您的启发。您是否尝试过
this.val(x);
…?$this.val()
应该可以工作,可能是选择
值有问题,尝试了报警/console.logging?嗯..发生的事情是当我有$this.val(选择)时最后将所有选择选项的值更改为3或选择的任何内容。因此OP基本上可以像这样使用它。选择器。谢谢,你知道为什么选择器的值对我来说是未定义的吗?@HyungSuh是因为你使用了$.plugin
而不是$.fn.plugin
?这是一个非常容易的错误,而且当这个不会
//** Get selector **//
// Set empty variables to work with
var attributes = {}, // Empty object
$selector = ""; // Empty selector
// If exists...
if(this.length) {
// Get each node attribute of the selector (class or id)
$.each(this[0].attributes, function(index, attr) {
// Set the attributes in the empty object
// In the form of name:value
attributes[attr.name] = attr.value;
});
}
// If both class and id exists in object
if (attributes.class && attributes.id){
// Set the selector to the id value to avoid issues with multiple classes
$selector = "#" + attributes.id
}
// If class exists in object
else if (attributes.class){
// Set the selector to the class value
$selector = "." + attributes.class
}
// If id exists in object
else if (attributes.id){
// Set the selector to the id value
$selector = "#" + attributes.id
}
// Output
// console.log($selector);
// e.g: .example #example