jQuery为变量注入一个新值

时间:2016-01-12 23:01:05

标签: jquery

所以,我有以下js:

var main = jQuery(this).parents('.top');    

main.find('.top_left').removeClass("s7").addClass("s4");
main.find('.top_right').removeClass("s5").addClass("s4");

有三件事情会改变:.find, .removeClass, .addClass

有没有办法将整个事物作为一个变量,然后将值“注入”到每个字段中,如下所示?

var rhp_left = jQuery(this).parents('.top');    
var rhp_total= rhp_left.find(A).removeClass(B).addClass(C);

然后以某种方式为其添加了一个新的A,B,C值:A = '.top_right'这样的事情。

有什么建议吗?

由于

2 个答案:

答案 0 :(得分:2)

我建议创建一个接受3个参数的JavaScript function。然后调用该函数并将其传递给所需的值。您可以将函数配置为接受jQuery对象,选择器字符串,类名等。

例如:

  

o =采取行动的对象   f =在对象内找到的选择器
  r =要删除的类
  a =要添加的类

function alter(o, f, r, a) {
  jQuery(o).find(f).removeClass(r).addClass(a);
}

jQuery('#go_trigger').on('click', function() {
  alter('#item1', '.first_word', 'upper',   'blue');
  alter('#item2', 'input',       'small',   'red');
  alter('#item2', 'p.bgcolor',   'bgcolor', 'bold');
});
.blue    { color: blue;}
.upper   { text-transform: uppercase;}
.bgcolor { background-color:grey;}
.bold    { font-weight: bold;}
.small   { font-size: .5em;}
.red     { color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="item1">
  <span class="first_word upper">Hello</span>
  <span class="second_word upper">World</span>
</div>
<div id="item2">
  <input type="text" class="small" value="an input" />
  <p class="bgcolor">Testing...</p>
  <p>Unaffected.</p>
</div>

<button type="button" id="go_trigger">CLICK HERE</button>

答案 1 :(得分:1)

虽然您已经接受了答案,但我认为我可以稍微扩展一下这些可能性并提供一种替代方法来扩展jQuery原型并将功能添加为插件:

// wrapping the plugin code in an Immediately-Invoked
// Function Expression ("IIFE"), so that the function
// is invoked when it's encountered rather than
// having to be called subsequently:
(function($) {

  // defining the name of the plugin 'findAndSwitchClasses',
  // and allowing user-supplied arguments to the plugin
  // the 'opts' variable:
  $.fn.findAndSwitchClasses = function(opts) {

    // defining the default settings:
    var settings = $.extend({
      'descendantSelector': '.top_left',
      'classToRemove': 's7',
      'classToAdd': 's4'

    // updating the defaults - using $.extend() - to
    // override the defaults with user-supplied
    // arguments:
    }, opts);

    // returning the collection supplied to the plugin,
    // 'this', here, is the jQuery collection:
    return this.each(function() {

      // this is a DOM Node inside the each(),
      // wrapping that Node with jQuery to
      // allow jQuery methods to be called:
      $(this)

        // finding the descendant elements
        // matching the supplied selector:
        .find(settings.descendantSelector)

        // removing the supplied class:
        .removeClass(settings.classToRemove)

        // adding the supplied class:
        .addClass(settings.classToAdd);
    });
  };

// passing jQuery into the function, allowing the
// plugin to make use of the $ alias (for brevity):
})(jQuery)

// using the defaults:
$('#main').findAndSwitchClasses();

// using alternative settings to
// override the defaults:
$('#main').findAndSwitchClasses({
  'descendantSelector': '.top_right',
  'classToRemove': 's5'
});

&#13;
&#13;
(function($) {
  $.fn.findAndSwitchClasses = function(opts) {
    var settings = $.extend({
      'descendantSelector': '.top_left',
      'classToRemove': 's7',
      'classToAdd': 's4'
    }, opts);

    return this.each(function() {
      $(this)
        .find(settings.descendantSelector)
        .removeClass(settings.classToRemove)
        .addClass(settings.classToAdd);
    });
  };
})(jQuery)

$('#main').findAndSwitchClasses();

$('#main').findAndSwitchClasses({
  'descendantSelector': '.top_right',
  'classToRemove': 's5'
});
&#13;
div {
  box-sizing: border-box;
  min-height: 2em;
  width: 50%;
  float: left;
  border: 1px solid #000;
  padding: 0.25em;
}
#main div::before {
  content: attr(class);
}
.s4 {
  border-color: #f90;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  <div class="top_left s7">

  </div>
  <div class="top_right s5">

  </div>
</div>
&#13;
&#13;
&#13;

JS Fiddle demo

参考文献: