如何从Text转换为String,Jquery

时间:2014-09-25 09:13:34

标签: javascript jquery coffeescript

我在我的应用程序中有几个选择,如下所示:

<select class="select" id="t_0" name="t[0]">
  <option value="1">a</option>
  <option value="2">b</option>
  <option value="3">c</option>
  <option value="4">d</option>
</select>

<select class="select" id="t_1" name="t[1]">
  <option value="1">a</option>
  <option value="2">b</option>
  <option value="3">c</option>
  <option value="4">d</option>
</select>

我需要在我的Javascript / coffeescript中创建一个方法,如果所有选定的值都有文本:“b”,则返回true。

  _tAreB: -> 
    selecteds = $('select[id^=t_] option:selected').contents()
    for t in selecteds 
      return false unless t == "b"
    return true

==失败,因为tText,无法与String进行比较,如何将t转换为字符串?

更新: 如果在控制台上我做:

>a = $('select[id^=t_] option:selected').contents()
>a
<- ["b","b","a"]
>a.constructor.prototype
<- []
>a[0].constructor.prototype
<- Text {splitText: function, replaceWholeText: function, getDestinationInsertionPoints: function, substringData: function, appendData: function…}

2 个答案:

答案 0 :(得分:2)

您可以使用类似的coffeescript:

(($) ->
    checkForMatches = ->
        searchBucket = []

        # in this example, the select elements have a class '.select'
        selectedOptions = $ '.select option:selected'
        selectedCount = selectedOptions.length
        searchBucket.push option for option in selectedOptions when option.text is 'b'

        allMatch = searchBucket.length is selectedCount
        console.log allMatch
        return allMatch

    # try to test with a selected option set to 'bb'
    # note: currently this will print true since selected options match on document load
    $(checkForMatches)
)(jQuery)

this plunkr

中的完整示例

答案 1 :(得分:1)

正如您所提到的,您正在处理textstring之间的比较。实际上有一种简单的方法可以解决这个问题:引用textContent的{​​{1}}。

(不幸的是,我不做coffeescript,但这里是JS中编译过的coffeescript的变化)

text

这是一个小提琴演示:

http://jsfiddle.net/jpattishalljr/8qmrogL7/1/