简体   繁体   English

jQuery XPath插件设置属性

[英]jQuery XPath plugin setting attribute

This question is about Sergey Ilinsky's jQuery XPath plugin. 这个问题与Sergey Ilinsky的jQuery XPath插件有关。 I have an xml file which I navigate it through this plugin. 我有一个xml文件,可以通过此插件对其进行导航。 The file itself is not important to see. 文件本身并不重要。 The question is more related to functionality of the plugin. 问题与插件的功能有关。

        var elemList = $(xmlDoc).xpath("call-script/option" + xpathExtension);
        for (var i = 0; i < elemList.length; i++) {
            if (elemList[i].getAttribute('text') != null) {
                alert(elemList[i].getAttribute('text'));
                //elemList[i].getAttribute('text') = 'example';
            }
        }

I would like to set the text attribute of the selected node as shown in commented out line. 我想设置选定节点的文本属性,如注释行所示。 getAttribute works like a charm when I use it only for reading purposes. 当我仅将getAttribute用于阅读目的时,它就像是一种魅力。 I would like to assign it with some kind of a setAttribute function which is not available. 我想给它分配某种不可用的setAttribute函数。 Any help from you would be much appreciated. 您的任何帮助将不胜感激。

Plugin's link: http://plugins.jquery.com/xpath/ 插件链接: http : //plugins.jquery.com/xpath/

Plugin's version: 0.2.4 插件版本:0.2.4

Edit: I think I should share part of my xml to give a better understanding. 编辑:我想我应该共享我的xml的一部分,以便更好地理解。

<?xml version="1.0"?>
<call-script say="Good morning">
    <option text="caller asks for blah">
    ...
       ...
    ...
    </option>
    <option text="caller requests blah">
    ...
       ...
    ...
    <option text="caller would like to blah">
    ...
       ...
    ...
    </option>
</call-script>

You've already got jQuery, so you can be a little more efficient if you use jQuery's .attr() function, which does double-duty as both a getter and setter depending on the arguments. 您已经有了jQuery,因此,如果您使用jQuery的.attr()函数,该函数会效率更高一点,该函数根据参数同时充当getter和setter的双重职责。 The $.each() function can be used here as well. $.each()函数也可以在这里使用。

Rewriting your sample: 重写示例:

$.each(elemList, function(key, element) {   // iterate over each thing in elemList
    if (element.attr('text') !== null) {   // without 2nd argument, just returns the value
        alert(element.attr('text'));   // same
        element.attr('text', 'example');   // with 2nd argument, sets the value
    }
});

http://api.jquery.com/attr/ http://api.jquery.com/attr/

Looks like there is a setAttribute function as well. 看起来也有setAttribute函数。

 elemList[i].setAttribute('text','example');

This has fixed my problem. 这解决了我的问题。 Sorry for hassling you. 对不起,麻烦您了。

Tutorial link: http://www.w3schools.com/xml/met_element_setattribute.asp 教程链接: http : //www.w3schools.com/xml/met_element_setattribute.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM