如何在childNode事件上更改parentNode样式属性

时间:2011-05-11 02:52:34

标签: javascript

嘿伙计们,我有这样的UL:

<ul id="list">
    <li class="something">
        <div class="btns" onclick="add(this)"> + </div>
        <div class="btns" onclick="sub(this)"> - </div>
    </li>
    <li class="something new">
        <div class="btns" onclick="add(this)"> + </div>
        <div class="btns" onclick="sub(this)"> - </div>
    </li>
</ul>

CSS明智地,类'something'包含背景图像。

我想在这里实现的是,当进行add()或sub()函数调用时,调用该元素的元素的parentNode的background-image属性发生了变化......

所以这样,我不必为每个元素制作ID,并且可以重用相同的函数......

我所拥有的是这样的东西,但它不起作用(相反,我写的代码是错误的):

function add(x)
{
    var y = x.parentNode.style;

    if (y.backgroundImage == 'url("../assets/1.png")'
    {
        y.backgroundImage = 'url("../assets/2.png")';
    } else if (y.backgroundImage == 'url("../assets/2.png")'
        y.backgroundImage = 'url("../assets/3.png")';
    ...
    ... so on so forth...
}

整体逻辑本身可能很差,所以我也接受新建议......

编辑#1:添加更多详细信息以解释当前情况...

基本上,有一个3x3网格,其中填充了li,而背景图像使用点表示当前数量。每个li里面有两个按钮,可以加减。点击每个,背景图像应该改变以表示当前数量......这必须独立于不同的li ...

5 个答案:

答案 0 :(得分:1)

我同意RobG的观点,即使用类更适合 - 特别是如果您决定使用框架。在这种情况下你不想在这里采取其他一些方法:

针对计算机样式进行了更新 - 将评论版本保留在帖子的底部: 这个的主要区别在于它获取内联样式或计算版本的背景图像(例如,如果它由类设置)。

要获取计算样式,请查看quirksmode.org。特别是getstyles page的底部。

这是fiddle在jsfiddle中不起作用(有点累,但我认为它与我在工作中使用IE6有关...),但如果你在正常环境中在本地进行它可以正常工作

function add(x) {
    var parent = x.parentNode;
    var y = parent.currentStyle['backgroundImage'] || document.defaultView.getComputedStyle(parent,null).getPropertyValue('backgroundImage');
    switch(true)
    {
        case (y.indexOf("1.png")!=-1):
            parent.style.backgroundImage = 'url("http://www.wskidmore.com/2.png")';
            break;
        case (y.indexOf("2.png")!=-1):
            parent.style.backgroundImage = 'url("http://www.wskidmore.com/3.png")';
            break;
        case (y.indexOf("3.png")!=-1):
            parent.style.backgroundImage = 'url("http://www.wskidmore.com/1.png")';
            break;
    }
} 

过时,但用逻辑评论。

function add(x) {
        var y = x.parentNode.style.backgroundImage;
    // using indexOf will avoid the possible quote issue and possibly other odd browser quirks
    // switch true means it will do the first case it finds that evaluates to true
    switch(true)
    {
        // indexof means it looks through your string for the given substring
        // and returns the position so, "abc".indexOf("b") returns 1 (its 0 based)
        // if it doesnt find it anywhere it returns -1
        // so for our switch, it looks inside the backgroundImage string
        // url("../assets/x.png") no-repeat 50% 50%
        // or whatever it may be for the part "1.png"
        // if it finds it, it will return 5, or 8, or whatever the position is
        // if not it returns -1
        // so when this gets evaluated we check for "not -1"
        case (y.indexOf("1.png")!=-1):
          // if this case is true, then everything between the : and break;
          // will be performed, then it exits the switch
          y = 'url("../assets/2.png")';
          break;      
        case (y.indexOf("2.png")!=-1):
          y = 'url("../assets/3.png")';
          break;      
        case (y.indexOf("3.png")!=-1):
          y = 'url("../assets/4.png")';
          break;      
    }
}

答案 1 :(得分:0)

使用getElementsByName()函数,在要更改的所有节点上设置相同的名称。

function add(x) {
  var elements = document.getElementsByName("somename");
  /* Iterate over the array and set the .style.* elements as needed */
}

http://www.w3schools.com/jsref/met_doc_getelementsbyname.asp

答案 2 :(得分:0)

您的代码应该可以正常工作,除非您将现有背景图像与错误匹配。它不会返回与您设置时相同的引号。

//When setting the url property, you need to wrap the actual URI in double quotes
//and then wrap the whole thing in single quotes to indicate to JS that it's a string
y.backgroundImage = 'url("../assets/1.png")'; //set background image

//y.backgroundImage now has a value of 'url(../assets/1.png)'    

//Here you try to match the value of y.backgroundImage against the string you
//originally stored in it, but that won't work
y.backgroundImage == 'url("../assets/1.png")'; //false

//The backgroundImage property returns a string that has the quotes stripped
//out of the inside of the URL definition
y.backgroundImage == "url(../assets/1.png)";  //true

答案 3 :(得分:0)

您好像找到了parentNode。设置样式对象属性的替代方法,请考虑添加和删除类。一些简单的功能是:

var yourLib = {
  dom: {},
  util: {}
};

/* Check if an element has a particular class name
*/
yourLib.dom.hasClassName = function(el, cName) {
    if (typeof el == 'string') el = document.getElementById(el);

    var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
    return el && re.test(el.className);
}

/* Add a class name if element doesn't already have it
*/
yourLib.dom.addClassName = function(el, cName) {

    if (typeof el == 'string') el = document.getElementById(el);

    if (!yourLib.dom.hasClassName(el, cName)) {
        el.className = yourLib.util.trim(el.className + ' ' + cName);
    }
}

/* Remove a class name if element has it
*/
yourLib.dom.removeClassName = function(el, cName) {

    if (typeof el == 'string') el = document.getElementById(el);

    if (util.dom.hasClassName(el, cName)) {
        var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
        el.className = yourLib.util.trim(el.className.replace(re, ''));
    }
}

/* Remove leading and trailing whitespace and reduce
** multiple intermediate whitespaces to a single space
*/
yourLib.util.trim = function(s) {
  return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
}

答案 4 :(得分:0)

好的,所以我让它运转了,这是以后偶然发现的人的解决方案......

function add(x)
{
    var y = x.parentNode.style.backgroundImage;
    if ((y == '') || (y.indexOf("3_0.png") != -1))
        x.parentNode.style.backgroundImage = 'url(../_assets/3_1.png)';
    else if (y.indexOf("3_1.png") != -1)
        x.parentNode.style.backgroundImage = 'url(../_assets/3_2.png)';
    else if (y.indexOf("3_2.png") != -1)
        x.parentNode.style.backgroundImage = 'url(../_assets/3_3.png)';
    else if (y.indexOf("3_-3.png") != -1)
        x.parentNode.style.backgroundImage = 'url(../_assets/3_-2.png)';
    else if (y.indexOf("3_-2.png") != -1)
        x.parentNode.style.backgroundImage = 'url(../_assets/3_-1.png)';
    else if (y.indexOf("3_-1.png") != -1)
        x.parentNode.style.backgroundImage = 'url(../_assets/3_0.png)';
}

基本上,在WSkid的帮助下(谢谢!)我使用'indexOf'来确定哪个是当前背景,并因此根据调用的函数而改变。这是添加功能的代码。