如何使用jquery获取元素的兄弟文本

时间:2016-07-09 17:38:13

标签: javascript jquery html text click

我有ul个列表,每个li我有2个span和一个a标记链接以及li的文字:

<li>
    <span>first name 1</span>
    <a>//icon to be selected</a>
    <span>last name 1</span>email address 1
</li>
<li>
    <span>first name 2</span>
    <a>//icon to be selected</a>
    <span>last name 2</span>email address 2
</li>
<!-- 
    multiple li 
-->
<li>
    <span>first name n</span>
    <a>//icon to be selected</a>
    <span>last name n</span>email address n
</li>

现在,如果用户在每个li标记中选择一个链接,则jquery我希望获得first nameemail address文字。我将很高兴得到答案。

1 个答案:

答案 0 :(得分:2)

使用jquery prev()next()选择器查找目标范围,并使用nextSibling属性查找span的兄弟文本。

&#13;
&#13;
KEYWORD: blah
&#13;
   @IBAction func onDateChanged(sender: AnyObject) {
    let dateFormatter = NSDateFormatter()

   // dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

    let strDate = dateFormatter.stringFromDate(datePicker.date)

    let timeinterval = NSTimeInterval.abs(17 * 60) //time in seconds
    let newDate = strDate.dateByAddingTimeInterval(-timeinterval)
    // ERROR =- on the above line I get an error saying that type String does not have a method called dateByAddingTimeInterval, however I made the string a NSDate value in the variable newDate.


    print("\(strDate) is the date on the datePicker @")
}
&#13;
$("a").click(function(){
    var name = $(this).prev().text();
    var email = $(this).next()[0].nextSibling.nodeValue.trim();
    console.log(name);
    console.log(email);
});
&#13;
&#13;
&#13;