如何根据是否选择了最近的单选按钮来显示 - 隐藏按钮?

时间:2017-10-09 10:05:16

标签: javascript jquery radio-button show-hide

假设我有两个测验问题。每个问题都有用于选择答案的单选按钮和一个清除答案按钮以清除答案。 仅当在相应的问题块中选择/取消选择答案时,清除按钮才会隐藏/显示。

如何选择/取消选择单选按钮是否是最近的问题块并相应地显示/隐藏清除按钮?

Here,is the screenshot of the scenario I am talking about.

而且,这是我目前正在使用的JS代码

jQuery(function($) {

if ($("input[type]").is(":radio")) {
    $(".answer").append("<button type='button' name='clear' >Clear</button>");
}

if ($("input[type=radio]:checked").length > 0) {
    $('button[name=clear]').show();
}
else{
    $('button[name=clear]').hide();
    }


$("input[type=radio]").on('click', function() {
    $nearest=  $(this).closest('.answer').find('button[name=clear]');
    $nearest.show();
});

$('button[name=clear]').on('click', function() {
    $(this).closest('.answer').find(':radio').prop('checked', false);
    $(this).hide();
});

if ($('.content').parent().hasClass("deferredfeedback")) {
    if ($('.answer .r0 input').prop('disabled')) {
        $("button[name=clear]").remove();
    }
} else {
    if (!($('div.im-controls').length)) {
        $("button[name=clear]").remove();
    }
}

});
在某个地方,我错过了一些我无法找到的东西,有人可以指导我吗?

2 个答案:

答案 0 :(得分:0)

为什么不在那里使用清除按钮并将其隐藏

CSS

.clearButton { display:none}

jQuery - 假设每个答案的容器都有类&#34;回答&#34;和
clear按钮有class&#34; clearButton&#34;:

$(function() {
  $(".answer").on("click","input[type=radio]",function() {
    $(this).closest(".answer").find(".clearButton").show();
  });
});

或兄弟姐妹:

$(function() {
  $(".answer").on("click","input[type=radio]",function() {
    $(this).siblings(".clearButton").show();
  });
});

清楚可以使用

  $(".answer").on("click",".clearButton",function() {
    $(this).siblings("input[type=radio]").prop("checked",false);
    $(this).hide();
  });

如果已检查某些无线电,则显示清除按钮onload:

$("[type=radio]:checked").trigger("click")

&#13;
&#13;
$(function() {
  $(".answer").on("click", "input[type=radio]", function() {
    $(this).closest(".answer").find(".clearButton").show();
  });


  $(".answer").on("click", ".clearButton", function() {
    $(this).siblings("input[type=radio]").prop("checked", false);
    $(this).hide();
  });


  $("[type=radio]:checked").trigger("click")

});
&#13;
.clearButton {
  display: none
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="answer">
  <label><input type="radio" name="answer1" value="1">Answer 1</label>
  <label><input type="radio" name="answer1" value="2">Answer 2</label>
  <label><input type="radio" name="answer1" value="3">Answer 3</label>
  <button type="button" class="clearButton">Clear</button> 
</div>
<hr/>
<div class="answer">
  <label><input type="radio" name="answer2" value="1">Answer 1</label>
  <label><input type="radio" name="answer2" value="2" checked>Answer 2</label>
  <label><input type="radio" name="answer2" value="3">Answer 3</label>
  <button type="button" class="clearButton">Clear</button> 
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试以下代码

Js Code here

package com.cygnet.lucene.component;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.search.highlight.TokenSources;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component
public class LuceneSearch {

    // Folder path where Lucene will create index files from #fileInputDirPath
    @Value("${lucene.indexDirPath}")
    String indexDirPath;

    public Map<String, String> searchContentFromFiles(String searchTerm) throws Exception {

        Map<String, String> fileWithRelativePathMap = new HashMap<>();

        // Get directory reference
        Directory dir = FSDirectory.open(Paths.get(indexDirPath));

        // Index reader - an interface for accessing a point-in-time view of a lucene
        // index
        IndexReader reader = DirectoryReader.open(dir);
        System.out.println("MaxDoc:::"+reader.maxDoc());
        // Create lucene searcher. It search over a single IndexReader.
        IndexSearcher searcher = new IndexSearcher(reader);



        // analyzer with the default stop words
        Analyzer analyzer = new StandardAnalyzer();

        // Query parser to be used for creating TermQuery
        QueryParser qp = new QueryParser("contents", analyzer); // Change

        System.out.println("searchTerm::"+searchTerm);

        // Create the query
        Query query = qp.parse(searchTerm);


        // Search the lucene documents
        TopDocs hits = searcher.search(query, 10000);

        System.out.println("hits::"+hits.totalHits);
        /** Highlighter Code Start ****/
        fileWithRelativePathMap.put("totalCount", String.valueOf(hits.totalHits));
        // Uses HTML &lt;B&gt;&lt;/B&gt; tag to highlight the searched terms
        Formatter formatter = new SimpleHTMLFormatter();

        // It scores text fragments by the number of unique query terms found
        // Basically the matching score in layman terms
        QueryScorer scorer = new QueryScorer(query);

        // used to markup highlighted terms found in the best sections of a text
        Highlighter highlighter = new Highlighter(formatter, scorer);

        // It breaks text up into same-size texts but does not split up spans
        Fragmenter fragmenter = new SimpleSpanFragmenter(scorer, 10000);

        // breaks text up into same-size fragments with no concerns over spotting
        // sentence boundaries.
        // Fragmenter fragmenter = new SimpleFragmenter(10);

        // set fragmenter to highlighter
        highlighter.setTextFragmenter(fragmenter);


        // Iterate over found results
        for (int i = 0; i < hits.scoreDocs.length; i++) {
            int docid = hits.scoreDocs[i].doc;
            Document doc = searcher.doc(docid);

            String rPath = doc.get("path");
            String fileName = doc.get("fileName");

            // Printing - to which document result belongs
            System.out.println("Path " + " : " + rPath);

            // Get stored text from found document
            String text = doc.get("contents");

            // Create token stream
            TokenStream stream = TokenSources.getAnyTokenStream(reader, docid, "contents", analyzer);

            // Get highlighted text fragments
            String[] frags = highlighter.getBestFragments(stream, text, 10);
            fileWithRelativePathMap.put(fileName, rPath.replace("\\", "/"));

            for (String frag : frags) {
                System.out.println(frag);
            }
        }
        dir.close();
        return fileWithRelativePathMap;
    }
}

click here to show jsFiddle demo